微信小程序实现类似Vue中的computed、watch功能

微信小程序实现类似Vue中的computed、watch功能

构建npm

  1. 创建包管理器

    进入小程序后,打开终端,点击顶部"视图" - "终端"

    新建终端

    使用 npm init -y初始化包管理器,生成一个package.json文件

  2. 安装 npm 包

    javascript 复制代码
    npm install --save miniprogram-computed
  3. 构建npm

    点击开发者工具中的菜单栏:工具 --> 构建 npm

使用

在自定义组件中,以require的方式引入

  1. computed 基本用法

    javascript 复制代码
    const computedBehavior = require('miniprogram-computed').behavior
    Component({
      behaviors: [computedBehavior],
      data: {
        a: 1,
        b: 1,
      },
      computed: {
        sum(data) {
          // 注意: computed 函数中不能访问 this ,只有 data 对象可供访问
          // 这个函数的返回值会被设置到 this.data.sum 字段中
          return data.a + data.b
        },
      },
      methods: {
        onTap() {
          this.setData({
            a: this.data.b,
            b: this.data.a + this.data.b,
          })
        },
      },
    })
  2. watch 基本用法

    javascript 复制代码
    const computedBehavior = require('miniprogram-computed').behavior
    
    Component({
      behaviors: [computedBehavior],
      data: {
        a: 1,
        b: 1,
        sum: 2,
      },
      watch: {
        'a, b': function (a, b) {
          this.setData({
            sum: a + b,
          })
        },
      },
      methods: {
        onTap() {
          this.setData({
            a: this.data.b,
            b: this.data.a + this.data.b,
          })
        },
      },
    })
相关推荐
小徐_23332 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
古夕6 小时前
第三方 SSO 接入实践:redirect_uri 编码、回调一致性与跨项目联调
前端·vue.js
Ruihong6 小时前
Vue withDefaults 转 React:VuReact 怎么处理?
vue.js·react.js·面试
稀土熊猫君8 小时前
一个人能做出什么开源项目?
vue.js·后端·开源
DarkLONGLOVE1 天前
快速上手 Pinia!Vue3 极简状态管理使用教程
javascript·vue.js
宸翰1 天前
解决 uni-app App 端 vue-i18n 占位符丢失:封装跨端可用的 tf 格式化方法
前端·vue.js·uni-app
用户2136610035722 天前
VueRouter进阶-动态路由与嵌套路由
前端·vue.js
暴走的小呆2 天前
Vue 2 中 Object 的变化侦测:从 getter/setter 到 Dep、Watcher、Observer
vue.js
英勇无比的消炎药2 天前
TinyVue v-auto-tip: 文本超长自动提示的优雅方案
vue.js
时光足迹2 天前
腾讯云 TRTC UniApp SDK 从入门到上线
前端·vue.js·uni-app