First experience in WeChat mini program development
Component instance
this.selectComponent('.classSelector')
##Introduction
Taro
Vant Weapp is introduced in Taro and cannot be called directly through the third-party NPM package.
- Find the Vant-weapp download file package on github and copy the corresponding
- dist
directory Go to the project
/src/components/vant-weappdirectory.
In - config.usingComponents
of the
Pagescorresponding file, configure the components required for each page. (The so-called global registration of components cannot be done in
app.js.)
config = { navigationBarTitleText: '首页', usingComponents: { "van-button": "../../components/vant-weapp/button/index", "van-popup": "../../components/vant-weapp/popup/index" } }
- After using the
- Vant-weapp
component,
taroThe build will
automatically copy the corresponding components to dist/components, and
Vant-weapp’s components also depend on the tool library
/src/components/vant-weapp/wxs, the tool library
tarowill not be automatically copied to dist
. Therefore, we need to modify the
config.copy.patternsin the
/config/index.jsfile so that it will be automatically copied to the
distcorresponding directory during compilation. Down.
copy: { patterns: [ { from: 'src/components/vant-weapp/wxs/', to: 'dist/components/vant-weapp/wxs/' } ], options: { } },
- Since the unit used in the style of
- Vant-weapp
is
px, it will be compiled into # by
taro##rpx
to adapt each device. You can prevent unit conversion by modifyingconfig.weapp.module.pxtransform.selectorBlackList
in the/config/index.js
file.pxtransform: { enable: true, config: { }, selectorBlackList: [ /^.van-.*?$/, // 这里是vant-weapp中className的匹配模式 ] },
Copy after login
##ec-canvas
is the WeChat applet version ofECharts.
iconfont
Download it locally, don’t change anything, and put it in the specified location.
This resource will not be automatically copied to thedist/
folder, so it needs to be copied by modifying the configuration file.copy: { patterns: [ ... { from: 'src/assets/fonts/', to: 'dist/assets/fonts/' }, ... ], options: { } }
Then, in the
app.js entry file, import './assets/fonts/iconfont.css'.
Custom component
Component passing parameters to the outside
this.triggerEvent(
'eventType',
{
key: value, //这里定义的键值对,在父组件中,通过args.detail.key获取;
},
{
bubbles: true, //事件属性:是否冒泡;
capturePhase: true, //事件属性: 是否可捕获;
}
)
Copy after login
Slot
this.triggerEvent( 'eventType', { key: value, //这里定义的键值对,在父组件中,通过args.detail.key获取; }, { bubbles: true, //事件属性:是否冒泡; capturePhase: true, //事件属性: 是否可捕获; } )
Usage is the same as Vue
.
Note
: The style defined within the component for slot will not work. The style of the structure passed in slot can only be defined at the location where the component is called.
Development obstacles
#Taro
<span style="font-size: 14px;">Switch custom tabBar</span>
When Tab (config.tabBar.custom = true in app.jsx
), it needs to be in the life cycle of the corresponding Tab page componentDidShow:
if (typeof this.$scope.getTabBar === 'function' && this.$scope.getTabBar()) { this.$scope.getTabBar().setData({ selected: 1 }) }
Note that it is
this.$scope.getTabBar. The layer coverage problem caused by Canvas
canvas
is a native component created by the client, and the level of the native component is the highest , so no matter howz-indexand mask interaction exist at the same time,is set, other components in the page cannot be placed on top of the native component.
So, if
canvas
canvas will be on the upper layer of the mask.
Solution:
Wrap a layer of structure outside
canvas- , and set the
- canvas
container through conditions (mask switch) The
hiddenattribute.
Through
cover-view - ,
cover-image
Structurally,custom components,
cover-viewthrough positioning and upgrading the level, you can prevent Covered by
canvas.
Because the native component inserted later can cover the previous native component, please note:
- cover-view
- must be in canvas
followed by
;can be used to adjust the display order through flex
and - order
.
Only the
outermost - cover-view supports position: fixed
.
typeof - must be in canvas
wx:If
statement, the typeof operation cannot be used operator, the
typeof operator cannot be used in
{{}}, and can only be used in
wxs.
data initialization assignment
I don’t know when data is initialized, but when initializing data
, you cannot usethis Points to the current component instance (this is
this === void 0), that is,
data can only be initialized to a
constant.
When properties
methods are required to initialize
data, it can only be passed ## in the life cycle
attached #this.setData
Update the value of data
. <p>而且,如果<code>data.fn = this.methodName
,methodName
中如果调用了this
引用,这时this
指向的是data
,所以需要使用data.fn = this.methodName.bind(this)
。
vant-weapp库中的popup样式设置
popup
内容的大小不是由内容撑起来的,需要通过popup
组件的custom-class
定义一个类名,设置width
、height
来定义内容的尺寸。
vant-tree-select事件触发
在Taro
中的代码风格类React
,而vant-weapp
库中的代码风格为wxml
和wxs
风格。React
绑定事件是驼峰式,wxml
绑定事件是使用-
连字符分隔。
这就造成了Taro
使用vant-tree-select
组件时,onClickNav
和onClickItem
不会被vant-tree-select
识别,事件无法触发。
解决方案:对vant-tree-select
进行二次封装,事件原始触发通过this.$triggerEvent
传出驼峰式的事件类型,在Taro
中调用。
目前vant-weapp0.5.20
中,vant-tree-select
不支持单选。
props获取不到
驼峰式命名的事件无法触发[微信小程序]
注意@tarojs/cli
的版本,如最初用的1.2.0
版本就获取不到自定义组件传的参数,升级到最新版1.3.15
就可以了。
注意@tarojs/cli
的版本,如最初用的1.2.0
版本无法触发驼峰式命名的事件,升级到最新版1.3.15
,使用onClick-nav
形式绑定事件就可以了。
<span style="font-size: 14px;">Taro</span>
编译器无法自动将用到组件的<span style="font-size: 14px;">.wxs</span>
文件移动到<span style="font-size: 14px;">/dist</span>
相应目录下
手动移动。
在<span style="font-size: 14px;">微信开发者工具</span>
中运行<span style="font-size: 14px;">Taro</span>
代码,如果有<span style="font-size: 14px;">async/await</span>
,则regenerator is not defined。
将微信开发者工具
--> 右上角详情
--> 本地设置
里的配置全部关掉,如ES6转ES5
...。
定制echarts,引入报错
echarts.js
不需要再次编译,配置中新增编译时忽略echarts.js
。
weapp: { ... compile: { exclude: ['src/echarts-for-weixin/ec-canvas/echarts.js'] } }
getState()获取Store存储的数据
可以在<span style="font-size: 14px;">(dispatch, getState) => {</span>
中使用。
真机调试正常,预览/体验版空白(只有tabbar)
将"本地设置"--> "上传时进行代码保护"取消勾选。
<span style="font-size: 14px;">Taro</span>
中<span style="font-size: 14px;">className=''</span>
单引号赋值不起作用。
className
的值使用双引号包裹。
<span style="font-size: 14px;">Taro</span>
自定义组件内部使用<span style="font-size: 14px;">iconfont</span>
,不显示图标
参照外部样式类、全局样式类。
或者,组件单独引入iconfont.css
也可以。
获取路由参数
this.$router.params
<span style="font-size: 14px;">iconfont</span>
字符串渲染
如果将字体做变量使用,通用情况下无法正常显示。
- 需要将
icon: ['', '']
改写成icon: ['\ue61e', '\ue62d']
。 <rich-text nodes={}></rich-text>
使用Taro/微信小程序同步接口,仍异步返回结果
如使用Taro.getStorageSync('key')
获取缓存数据,结果仍是异步返回。同步接口需要结合await
使用,才是真正的同步。
分包
包大小限制
- 包超过2048KB,无法上传
分包操作
-
主包不需要特殊处理。
- navigateTab导航的页面必须在主包中。
-
分包
- 分包在
subPackages
配置。
- 分包在
pages: [ 'pages/login/login', 'pages/index/index', 'pages/manage/manage', 'pages/schedule/schedule', 'pages/inpidual/inpidual' ], 'subPackages': [ { 'root': 'pages-main', name: 'main', 'pages': [ 'acs/acs', 'acs-setting/acs-setting', 'setting-details/setting-details', 'current-energy/current-energy', 'history-energy/history-energy', 'electricity/electricity', 'runtime/runtime', 'daily-usage/daily-usage', 'onshift-record/onshift-record', 'schedule-details/schedule-details' ] }, ],
伪动态绑定事件
// index.wxml <input wx:if="{{metas.type == 'text' || metas.type == 'number' || metas.type == 'idcard' || metas.type == 'digit'}}" name="{{metas.name}}" type="{{metas.type}}" value="{{value}}" placeholder="{{metas.attrs.placeholder}}" bindchange="{{changeValidate}}" bindinput="{{inputValidate}}" bindblur="{{blurValidate}}" />
// index.js Component({ data: { changeValidate: '', inputValidate: '', blurValidate: '', eventType: 'input', rules: '', value: '', isRequired: false, validateState: '', //['validating', 'success', 'error'] validateMessage: '' }, observers: { rules(newV) { console.log('------=======') this.setData({ [`${this.data.eventType}Validate`]: 'onBlurValidate' }) } }, methods: { onBlurValidate (e) { this.onValidate(e, rule) }, onValidate (e, rule) { } } })
获取组件实例
refFormItem = (node, idx) => { if(this.formItem) { !this.formItem.includes(node) && this.formItem.push(node) } else { this.formItem = [node] } } ... clearValidate () { console.log(this.formItem) this.formItem.forEach(item => { item.clearValidate() }) } ... render () { const { fieldMetas } = this.props; return ( <Form className="form" onSubmit={this.submitForm.bind(this)}> { fieldMetas.map((meta, idx) => { return ( <form-item ref\={this.refFormItem} onValidate={this.gatherValidate.bind(this)} taroKey={meta.name} metas={meta} initialValue={this.findValue.call(this, meta.name)}> </form-item> ) }) } <Button form-type="submit">按钮</Button> <Button onClick={this.clearValidate}>按钮</Button> </Form> ) }
styleIsolation: "apply-shared"
对于options.styleIsolation = "apply-shared"
的应用:
如果是组件包裹组件,内部组件设置该配置,外部组件的样式依旧无法影响内部组件,Page()或Component()注册的页面级的样式才能影响到组件内部样式。
推荐教程:《微信小程序》
The above is the detailed content of First experience in WeChat mini program development. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to
