1.对于WePY中的methods属性,因为与Vue中的使用习惯不一致,非常容易造成误解,这里需要特别强调一下:WePY中的methods属性只能声明页面wxml标签的bind、catch事件,不能声明自定义方法,这与Vue中的用法是不一致的。
// 错误示例
import wepy from 'wepy';
export default class MyComponent extends wepy.component {
methods = {
bindtap () {
let rst = this.commonFunc();
// doSomething
},
bindinput () {
let rst = this.commonFunc();
// doSomething
},
//错误:普通自定义方法不能放在methods对象中
customFunction () {
return 'sth.';
}
};
}
// 正确示例
import wepy from 'wepy';
export default class MyComponent extends wepy.component {
methods = {
bindtap () {
let rst = this.commonFunc();
// doSomething
},
bindinput () {
let rst = this.commonFunc();
// doSomething
},
}
//正确:普通自定义方法在methods对象外声明,与methods平级
customFunction () {
return 'sth.';
}
}
2.WePY中的组件都是静态组件,是以组件ID作为唯一标识的,每一个ID都对应一个组件实例,当页面引入两个相同ID的组件时,这两个组件共用同一个实例与数据,当其中一个组件数据变化时,另外一个也会一起变化。如果需要避免这个问题,则需要分配多个组件ID和实例。
<template>
<view class="child1">
<child></child>
</view>
<view class="child2">
<anotherchild></anotherchild>
</view>
</template>
<script>
import wepy from 'wepy';
import Child from '../components/child';
export default class Index extends wepy.page {
components = {
//为两个相同组件的不同实例分配不同的组件ID,从而避免数据同步变化的问题
child: Child,
anotherchild: Child
};
}
</script>
3.WePY中,在父组件template模板部分插入驼峰式命名的子组件标签时,不能将驼峰式命名转换成短横杆式命名(比如将childCom
转换成child-com
),这与Vue中的习惯是不一致。
4.当需要循环渲染WePY组件时(类似于通过wx:for
循环渲染原生的wxml标签),必须使用WePY定义的辅助标签<repeat>
<template>
<!-- 注意,使用for属性,而不是使用wx:for属性 -->
<repeat for="{{list}}" key="index" index="index" item="item">
<!-- 插入<script>脚本部分所声明的child组件,同时传入item -->
<child :item="item"></child>
</repeat>
</template>
<script>
import wepy from 'wepy';
// 引入child组件文件
import Child from '../components/child';
export default class Index extends wepy.page {
components = {
// 声明页面中要使用到的Child组件的ID为child
child: Child
}
data = {
list: [{id: 1, title: 'title1'}, {id: 2, title: 'title2'}]
}
}
</script>
5.(1).可以通过使用.sync
修饰符来达到父组件数据绑定至子组件的效果;
(2).可以通过设置子组件props的twoWay: true
来达到子组件数据绑定至父组件的效果;
(3).既使用.sync
修饰符,同时子组件props
中添加的twoWay: true
时,就可以实现数据的双向绑定了。
// parent.wpy
<child :title="parentTitle" :syncTitle.sync="parentTitle" :twoWayTitle="parentTitle"></child>
data = {
parentTitle: 'p-title'
};
// child.wpy
props = {
// 静态传值
title: String,
// 父向子单向动态传值
syncTitle: {
type: String,
default: 'null'
},
twoWayTitle: {
type: String,
default: 'nothing',
twoWay: true
}
};
6.目前总共有三种事件后缀:
-
.default
: 绑定小程序冒泡型事件,如bindtap
,.default
后缀可省略不写; -
.stop
: 绑定小程序捕获型事件,如catchtap
; -
.user
: 绑定用户自定义组件事件,通过$emit
触发。注意,如果用了自定义事件,则events中对应的监听函数不会再执行。