微信小程序之计算属性computed--时间插件

904 阅读1分钟

引言

由于在平时开发项目的过程中,计算属性是经常被使用到的,可用于快速计算视图view中显示的属性,这些计算将被缓存,并且只在需要时更新。但是在接触微信小程序开发之初,发现小程序官方开发api中并没有提供计算属性,例如 computed...

在公司项目中的使用场景:由于公司APP和小程序端页面改版。根据新版原型图小程序UI框架的pickerTime组件就不支持了,需要开发自定义时间插件,通过年月来动态计算天数。

虽然小程序api里面是没有提供computed属性,但是在扩展组件里面提供了computed 方法,需要我们自己去安装使用,具体步骤如下。

  1. 安装
npm install --save miniprogram-computed
  1. 在封装的组件里面引入并声明
const computedBehavior = require('miniprogram-computed');

Component({
  behaviors: [computedBehavior],
  properties: {
    'visible': {
      type: Boolean,
    },
    'timetype': {
      type: String
    },
  },
  1. 定义 computed
computed: {
  daysList(data) {
  const dayCount = getDayCountOfMonth(data.year, data.month-1);
  const computedDayList = new Array();
  for (let i = 1; i <= dayCount; i++) {
    computedDayList.push(i)
  }
  return computedDayList;
  },
},

computed 里面的函数是不需要被定义的,并且该函数不能访问 this,只能访问 data 对象,返回来的值会被设置到 this.data.xx 中。 如果函数中不可避免的需要访问 this,需要用 watch 来代替。

Github路径: github.com/littleHmm

🍁完整可用的时间组件代码可到Git上下载🍁
🍁有不对的地方希望小伙伴多多指教🍁