import Store from 'swan-store';
export default new Store({
state: {
counter: 0,
num: 110,
arr: [1, 2, 3, 4, 5, 6, 7],
test: []
},
mutations: {
count(state, payload) {
return state.counter += payload;
},
count1(state, payload) {
return state.num += payload;
},
addarr(state, payload) {
state.test = payload;
},
},
actions: {
countAsync(store, payload) {
return new Promise(resolve => {
setTimeout(() => {
store.commit('count1', payload);
resolve();
}, 1000);
});
},
},
getters: {
arrLength(state) {
return state.arr.length;
}
}
});
import Store from '../../store/swan-store';
Page({
data: {
number: 0,
name: 'SWAN',
items: [1, 2, 3, 4, 5, 6, 7, 8, 9],
test: {
a: 100,
b: 200
}
},
computed: {
test2() {
return this.data.test.a + 'Test2'
},
test3() {
return this.data.test.b + 'Test3'
}
},
watch: {
test(newVal) {
console.log('test发生变化', newVal);
}
},
onLoad() {
Store.install(this);
Store.commit('addarr', 1);
Store.dispatch('countAsync', 5);
Store.replaceState({
counter: 955
});
const a = Store.subscribe((type, state) => {
i++;
console.log(type, state);
if (i > 3) a();
});
}
})
<view>{{$state.counter}}</view> // 获取store里的值
<view>{{$state.num}}</view>
<view>{{$state.arr}}</view>
<view>{{$getter.arrLength}}</view> // store里的getter
<view>{{tag}}</view>
<view>{{test2}}</view> // 计算属性
<view>{{test3}}</view>