vuex 组合式API实践指南
1. 定义store
store/index.js 创建store对象并导出store
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import { store } from "quasar/wrappers"; import { createStore } from "vuex"; export default store(function () { const Store = createStore({ state: { num:'1' }, mutations: { addNum(state){ state.num ++; }, addNum2(state,val){ state.num +=val }, }, actions: { }, modules: { } });
return Store; });
|
2. 使用store
2.1. 在模板中调用声名的num
1
| <div>$store.state.num:{{$store.state.num}}</div>
|
1 2 3 4 5 6 7 8 9
| <script> import { useStore } from 'vuex' export default defineComponent({ setup() { const store = useStore() } });
</script>
|
2.2. 对state.num进行操作
vuex的store状态更新的唯一方式:提交 mutation
同步操作可以直接在mutatuions中直接进行
不能直接对state直接操作store.state.num +=44;
,这样会丢失响应性。
1 2 3
| <div class="num"> $store.state.num:{{$store.state.num}}</div> <q-btn label="num+1" @click="numplus1"/> <q-btn label="num+3" @click="numplus3"/>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <script> import { useStore } from 'vuex' export default defineComponent({ setup() { const store = useStore() const numplus1 =()=>{ store.commit('addNum') } const numplus3 =()=>{ store.commit('addNum2',3) } return{ numplus1, numplus3, } } });
</script>
|