// src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++;
}
},
actions: {
increment ({ commit }) {
commit('increment');
}
},
getters: {
count: state => state.count
}
});
// 在 main.js 中引入 store
// import Vue from 'vue';
// import App from './App.vue';
// import store from './store';
// new Vue({
// store,
// render: h => h(App)
// }).$mount('#app');
// 使用示例:
// this.$store.commit('increment'); // 直接调用 mutation 修改状态
// this.$store.dispatch('increment'); // 调用 action 触发 mutation 修改状态
// console.log(this.$store.getters.count); // 获取当前状态
Vuex Store 创建:
state
:存储应用的状态,例如 count
。mutations
:定义了如何修改状态的方法。increment
方法会将 count
增加 1。actions
:用于处理异步操作或复杂的业务逻辑。increment
动作会触发 commit
来调用对应的 mutation。getters
:用于获取状态的计算属性。这里我们定义了一个 count
getter 来获取 state.count
。在组件中使用:
this.$store.commit('increment')
直接调用 mutation 修改状态。this.$store.dispatch('increment')
调用 action 触发 mutation 修改状态。this.$store.getters.count
获取当前的状态值。引入和挂载:
main.js
中引入并挂载 store 到 Vue 实例中,这样所有的组件都可以访问到 store。下一篇:vue3+ts
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站