在小程序開發中,改變數據更新視圖用的是Page.prototype.setData方法,遇到一些複雜數據邏輯判斷時,代碼會寫的很繁瑣,這個時候就想嘗試在小程序內實現像Vue.js那樣的computed自動計算功能。以前有研究過Vue.js的依賴收集邏輯,就照葫蘆畫瓢搗鼓了一下。而數據變化後的視圖更新操做則是經過小程序內部的Page.prototype.setData原型函數來完成。javascript
使用rollup進行構建html
npm install
npm run build
,在dist目錄下生成打包文件將打包後的wxComputed.min.js
文件放在lib目錄中,在須要用到的頁面中引入java
<!--index.wxml-->
<view class="container">
<view>firstName</view>
<input bindinput="inputEvent" data-type="firstName" value="{{firstName}}" />
<view>lastName</view>
<input bindinput="inputEvent" data-type="lastName" value="{{lastName}}" />
<view>fullName: {{ fullName }}</view>
</view>
複製代碼
// index.js
import initComputed from '../../lib/wxComputed.min.js'
Page({
data: {
lastName: 'aa',
firstName: 'bb',
},
inputEvent(e) {
const {type} = e.currentTarget.dataset
this.setData({
[type]: e.detail.value,
})
},
// 這裏放入computed屬性
computed: {
// 這是一個函數,返回值爲此計算屬性的值
fullName() {
return this.data.lastName + '-' + this.data.firstName
},
},
onLoad() {
// 在onLoad生命週期中執行computed屬性初始化
initComputed(this)
},
})
複製代碼
項目地址:github.com/leegsen7/wx…
有什麼不足之處請你們不吝賜教,一塊兒學習。git