一,安装
npm i --save mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1
二,构建前删除(miniprogram_npm)文件夹
三,在根目录中创建ji文件夹名字自定义,引入的时候要注意
// 引入mobx模块
import { action, observable } from 'mobx-miniprogram'
// 创建store实例对象
export const store = observable({
state: 2, //定义数据
Code: '',
// 计算属性
get sum() {
return this.state + this.state
},
// action方法用来修改store中的数据
updateCode: action(function (step) {
// step 是传入的参数
this.Code = step
}),
updateState: action(function (step) {
this.state += step
}
})
四,在页面级ji中引入使用
// 把store中的共享数据和方法,绑定到页面或者组件中
import { createStoreBindings } from 'mobx-miniprogram-bindings'
// 在js中引入store
import { store } from '../../store/store.js'
Page({
// 页面初始数据
data: {
},
// 生命周期函数--监听页面加载
onLoad(options) {
// 使用store的参数和方法
this.storeRes = createStoreBindings(this, {
store,
fields:['sum','Code','state'],
actions:['updateCode','updateState']
})
},
// 生命周期函数 -- 监听页面显示
onShow(){
// 可以直接获取store中的数据,组件应该可以,我不来修改就是可以
console.log(store);
}
// 方法可以在事件中使用进行更改store中的数据
fnUpdataCode(){
this.updateCode(需要传入的参数)
// 也可以直接更改store中定义的数据
this.setData({ Code: '你好'})
},
// state数据更改
fnSum(){
this.updateState(1)
},
// 生命周期函数--监听页面卸载
onUnload() {
// 页面卸载清理数据
this.storeRes.destroyStoreBindings()
},
})
五,在组件中使用
// 组件中使用
// 导入数据源
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
// 导入store实例
import { store } from '../../libs/store.js'
Page({
// 我也不知道这是什么意思,但是需要
behaviors:[storeBindingsBehavior],
storeBindings:{
store,
fields:{
sumA:()=>store.sumA, //绑定第一种方式
sumB:(store)=>store.sumB,//绑定第二种方式
sum:'sum', //绑定第三种方式
},
// 需要绑定的方法
actions:{
updateCode:'updateCode'
}
},
methods: {
fn(){
this.updateCode()
}
}
})
六,在wxml中使用
// 在wxml中使用数据
<view>
{{ state }} // store数据使用
{{ Code }} // '你好'
{{ sum }} // +1
</view>
<view>
// 点击方法对store数据更新
<button bindtap="fnSum" data-step='1'>增加</button>
</view>
有大佬可以告诉我在js中使用store中的定义的数据是怎么获取吗?
ok我知道怎么获取了,我真是猪脑子!!!!!!!
fn(){
console.log(store);
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
console.log(store);
this.fn()
},