1.概念
全局?jǐn)?shù)據(jù)共享(又叫做:狀態(tài)管理)是為了解決組件之間數(shù)據(jù)共享的問題。
2.小程序中共享方案
在小程序中,可使用mobx-miniprogram配合mobx-miniprogram-bindings實現(xiàn)全局?jǐn)?shù)據(jù)共享mobx-miniprogram用來創(chuàng)建Store實例對象
mobx-miniprogram-bindings用來把Store中的共享數(shù)據(jù)或方法,綁定到組件或頁面中使用?
3.Mobx相關(guān)的包
npm install --save mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1
4.將store中的成員綁定到頁面中
4.1創(chuàng)建store.js
// 創(chuàng)建store實例對象
// 引入observable是定義store的包,action是定義修改store數(shù)據(jù)的包
import {
observable,
action
} from "mobx-miniprogram"
// 通過observalbe方法就可以創(chuàng)建store
export const store = observable({
// 數(shù)據(jù)字段-共享的數(shù)據(jù)
numA: 1,
numB: 2,
// 計算屬性 get代表就是只讀的
get sum() {
return this.numA + this.numB
},
// action方法,用來修改store中的數(shù)據(jù)(外界數(shù)據(jù)是不能更改的)
// action方法包裹方法才行
updateNum1: action(function (step) {
this.numA += step
}),
updateNum2: action(function (step) {
this.numB += step
})
})
4.2.頁面js文件
// 這個函數(shù)用于將 MobX store 綁定到小程序的頁面
import {createStoreBindings} from "mobx-miniprogram-bindings"
// 引入store
import {store} from "../../store/store"
* 生命周期函數(shù)--監(jiān)聽頁面加載
*/
onLoad(options) {
// this指的是當(dāng)前頁面,當(dāng)函數(shù)執(zhí)行完成后,有一個返回值,掛在在頁面上,作為屬性
// {包含是三個屬性}
// store數(shù)據(jù)源,fields需要的字段或者屬性,綁定在頁面上,actions保存需要的方法
this.storeBindings= createStoreBindings(this,{store,
fields:['numA','numB','sum'],
actions:['updateNum1']
})
},
4.3contact.wxml文件
<!--pages/contact/contact.wxml-->
<view>{{numA}}+{{numB}}={{sum}}</view>
<van-button type="primary" bindtap="btnHandler" data-step="{{1}}">numA+1</van-button>
<van-button type="danger" bindtap="btnHandler" data-step="{{-1}}">numA-1</van-button>
4.4contact.js文件
btnHandler(e){
this.updateNum1(e.target.dataset.step)
},
4.5頁面展示
5. 將store中的成員綁定到組件中
5.1組件的js
import {storeBindingsBehavior} from "mobx-miniprogram-bindings"
import {store} from "../../store/store"
behaviors:[storeBindingsBehavior],
storeBindings:{
//數(shù)據(jù)源
store,
fields:{
//映射關(guān)系
numA:"numA",
numB:"numB",
sum:"sum"
},
actions:{
updateNum2:"updateNum2"
}
},
5.2組件的wxml文件
<view>{{numA}}+{{numB}}={{sum}}</view>
<van-button type="primary" bindtap="btnHandler2" data-step="{{1}}">numA+1</van-button>
<van-button type="danger" bindtap="btnHandler2" data-step="{{-1}}">numA-1</van-button>
5.3 組件js文件
methods: {
btnHandler2(e){
this.updateNum2(e.target.dataset.step)
}
}
5.4頁面展示
?
?文章來源地址http://www.zghlxwxcb.cn/news/detail-511424.html
?文章來源:http://www.zghlxwxcb.cn/news/detail-511424.html
?
到了這里,關(guān)于微信小程序全局?jǐn)?shù)據(jù)共享的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!