【微信小程序】组件中properties与data的异同

本文探讨了组件开发中,properties中的公开属性与data中私有变量的区别,涉及类型定义、默认值处理和访问权限,并强调了属性与data合并后的注意事项。

相同点

组件的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中的变量重名,可能会出现覆盖问题

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值