-
小程序框架没有提供计算属性相关的 api ,但是官方为开发者提供了拓展工具库 miniprogram-computed。
-
该工具库提供了两个功能:
- 计算属性
computed - 监听器
watch
- 计算属性
一、安装 miniprogram-computed
- 在项目的根目录下,使用如下命令,将快速在根目录下初始化生成一个
package.json文件npm init -y - 安装 miniprogram-computed
npm install miniprogram-computed - 然后 在
微信开发者工具的左上角 点击 》工具》 构建 npm,构建成功后,将会在项目根目录下生成miniprogram_npm文件夹,可以在miniprogram_npm文件夹中看见构建的结果

二、计算属性 computed
-
如果需要在组件中使用计算属性功能,需要
miniprogram-computed库中导入ComponentWithComputed方法 -
在使用时:需要将
Component方法替换成ComponentWithComputed方法,原本组件配置项也需要写到该方法中。在替换以后,就可以新增computed以及watch配置项。注意事项:
1.
computed函数中不能访问 this ,但是提供了形参,代表data对象 2.计算属性函数的返回值会被设置到 this.data.sum 字段中
-
在项目的根目录下的 components 文件夹中(没有该文件夹的需要自己创建)新建 custom02 文件夹,并在该文件夹中创建 custom02组件(在文件夹上点击鼠标右键,选择
新建 component) -
找到项目根目录下的
app.json文件,增加如下代码,将 custom02组件注册为 全局组件{ // ...其他配置项 "usingComponents": { "custom02": "./components/custom02/custom02" } } -
在
pages/index.wxml中使用 custom02 组件<custom02 /> -
修改
components/custom02/custom02.js文件,Component方法替换成ComponentWithComputed方法import { ComponentWithComputed } from 'miniprogram-computed' ComponentWithComputed({ data: { a: 1, b: 2 }, // 计算属性 computed: { total(data) { // 不能使用 this 获取数据 console.log(this); // undefined return data.a + data.b } }, methods: {} }) -
修改
components/custom02/custom02.wxml文件<view>{{a}} + {{b}} = {{total}}</view>
三、监听器 watch
- 在使用时:需要将
Component方法替换成ComponentWithComputed方法,原本组件配置项也需要写到该方法中,在替换以后,就可以新增computed以及watch配置项。
-
在项目的根目录下的 components 文件夹中(没有该文件夹的需要自己创建)新建 custom03 文件夹,并在该文件夹中创建 custom03组件(在文件夹上点击鼠标右键,选择
新建 component) -
找到项目根目录下的
app.json文件,增加如下代码,将 custom03组件注册为 全局组件{ // ...其他配置项 "usingComponents": { "custom03": "./components/custom03/custom03" } } -
在
pages/index.wxml中使用 custom03 组件<custom03 /> -
修改
components/custom03/custom03.js文件,Component方法替换成ComponentWithComputed方法import { ComponentWithComputed } from 'miniprogram-computed' ComponentWithComputed({ data: { a: 1, b: 2 }, watch: { // key: 需要监听的数据 // value: 回调函数,参数时改变之后的数据 // a: function (newVal) { // console.log(`a更新之后的数据:` + newVal); // }, // b: function (newVal) { // console.log(`b更新之后的数据:` + newVal); // } // 监听多个数据 "a,b": function (a, b) { console.log(`a更新之后的数据:` + a); console.log(`b更新之后的数据:` + b); } }, methods: { updateData() { this.setData({ a: this.data.a + 1, b: this.data.b + 1 }) } } }) -
修改
components/custom03/custom03.wxml文件<view>a: {{a}}</view> <view>b: {{b}}</view> <button type="primary" bind:tap="updateData">更新数据</button>



![# [RPA] 使用八爪鱼进行高效网页数据采集](https://i-blog.csdnimg.cn/direct/c9f9494b214c4a0198f45ce83712103d.png)















