-
小程序框架沒有提供計算屬性相關的 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); // undefinedreturn 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>