原生微信小程序使用状态管理westore
# 主要文件包含如下,放到项目同目录位置
├── store.js -----------状态数据文件
└── utils
├── create.js -------核心文件
└── diff.js ---------核心文件
简单使用
// store.js
export default {
data: {
motto: '全局可用',
},
globalData: ['globalPropTest', 'ccc.ddd'],
logMotto: function () {
console.log(this.data.motto)
},
// 默认 false,为 true 会无脑更新所有实例
// updateAll: true
}
在app.js使用
// app.js
import store from './store'
App({
onLaunch: function () {
store.data.motto = 'app.js进行修改'
setTimeout(() => {
// 使用setTimeout,因为在此之前可能还没有挂载update()
store.update();
}, 0);
},
globalData: {
userInfo: null
}
})
在页面中使用
// pages\index\index.js
import store from '../../store'
import create from '../../utils/create'
create(store, {
data: {
...store.data, // ! 注意: 如果是tabbar页面,请必须在这里展开数据,否则数据为空
aaa: '私有数据,不放在store'
},
onShow() {
this.update()
},
onLoad: function () {
this.store.data.motto = '这里是更新数据'
this.update()
},
})
组件使用
import create from '../../utils/create'
// 根节点注册过store,这里就可以不用注册
create({
ready: function () {
// you can use this.store here
},
methods: {
// you can use this.store here
}
})