相同点
组件的wxml的{{}}中都可以绑定properties中定义的属性以及data中定义的变量
例如在组件index.js的properties中定义height,在data中定义data。
那么在组件wxml中都可以使用
Component({
/**
* 组件的属性列表
*/
properties: {
height: {
type: Number,
value: 600
}
},
/**
* 组件的初始数据
*/
data: {
width:600
},
})
<!--components/test-component/index.wxml-->
<view style="width:{{width}}rpx;height:{{height}}rpx;background:#C12222"></view>
效果
不同点
- properties(属性)中定义的变量是开放的,外部(page页面)可以访问
data中的数据是私有的,外部不能访问 - properties中type是必填的,value和observer是选填的。data中定义的变量必须有初始值否者会报 ** is not defined
- properties中可以使用Number作为一个默认值的处理,但是data中使用Number会被误认为是方法function
Component({
/**
* 组件的属性列表
*/
properties: {
height: {
type: Number,
}
},
data: {
width: 600,
index:Number
},
lifetimes: {
attached: function() {
console.log("data:", this.data)
console.log("properties:", this.properties)
},
detached: function() {
},
},
})
打印结果:
- properties中如果type是Number而且传入的value是String类型的数字的话,会自动去掉数字前面的0
如果页面想显示02 必须用String
Component({
/**
* 组件的属性列表
*/
properties: {
height: {
type: Number,
}
},
/**
* 组件的初始数据
*/
data: {
width: 600,
index: Number
},
lifetimes: {
attached: function () {
this.setData({
height: "02",
index: "02"
})
console.log("data:", this.data)
console.log("properties:", this.properties)
},
detached: function () {},
},
})
打印结果
可以看到height设置为‘02’后打印结果是2
注意
经过上面的例子我们可以发现一个问题,就是打印data和打印properties的结果是一样的。也就是properties和data经过编译后会进行合并。这里我们需要注意的是
properties中的变量不要和data中的变量重名,可能会出现覆盖问题