一 data 数据
在小程序组件中,用于组件模板渲染的私有数据,需要定义到 data 节点中,示例如下。
Component({
/**
* 组件的初始数据
*/
data: {
count: 0
}
})
二 methods 方法
在小程序组件中,事件处理函数和自定义方法需要定义到 methods 节点中,示例代码如下。
Component({
methods: { // 组件的方法列表:包含事件处理函数和自定义方法
// 事件处理函数
addCount() {
if (this.data.count >= this.properties.max) return
this.setData({
count: this.data.count + 1,
max: this.properties.max + 1
})
// 通过 this 直接调用自定义方法
this._showCount()
},
_showCount() { // 自定义方法建议以 _ 开头
wx.showToast({
title: 'count是' + this.data.count,
icon: 'none'
})
}
}
})
三 properties 属性
在小程序组件中,properties 是组件的对外属性,用来接收外界传递到组件中的数据,示例代码如下。
Component({
// 属性定义
properties: {
// 第一种方式:简化的方式:不需指定属性默认值时,可以使用简化方式
max: Number,
// 第二种方式:完整的定义方式
max: { // 完整定义属性的方式【当需指定属性默认值时,建议使用此方法】
type: Number, // 属性值的数据类型
value: 10 // 属性默认值
}
}
})
<my-test1 max="10"></my-test1>
四 data 和 properties 的区别
在小程序的组件中,properties 属性和 data 数据的用法相同,它们都是可读可写的,只不过:
-
data 更倾向于存储组件的私有数据。
-
properties 更倾向于存储外界传递到组件中的数据。
Component({
/**
* 组件的属性列表
*/
properties: {
// 完整的定义方式
max: {
type: Number,
value: 10
}
},
/**
* 组件的初始数据
*/
data: {
count: 0
},
/**
* 组件的方法列表
*/
methods: {
showInfo() {
console.log(this.data) // 输出结果:{count: 0, max: 10}
console.log(this.properties) // 输出结果:{count: 0, max: 10}
console.log(this.data === this.properties) // 结果为 true,证明 data 数据和 properties 属性在本质上是一样的,都是可读可写的。
}
}
})
五 使用 setData 修改 properties 的值
由于 data 数据和 properties 属性在本质上没有任何区别,因此properties 属性的值也可以用于页面渲染,可使用 setData 为 properties 中的属性重新赋值,示例代码如下。
// 在组件的 .wxml 文件中使用 properties 属性的值
<view>max属性的值是:{{max}}</view>
Component({
properties: {
max: {
type: Number,
value: 10
}
},
/**
* 组件的方法列表
*/
methods: {
// 点击事件处理函数
addCount() {
this.setData({ // 使用 setDate 修改属性的值
max: this.properties.max + 1
})
}
}
})