// store.js
import { createStore } from 'vuex';
// 创建一个新的 store 实例。
const store = createStore({
state() {
return {
count: 0
};
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
increment({ commit }) {
commit('increment');
}
},
getters: {
count: (state) => state.count
}
});
export default store;
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
const app = createApp(App);
app.use(store);
app.mount('#app');
// 在组件中使用
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
computed: {
...mapState(['count'])
},
methods: {
...mapActions(['increment'])
}
};
</script>
创建 Vuex Store:
store.js 文件中,我们导入了 createStore 函数,并创建了一个新的 Vuex store 实例。这个实例包含了 state、mutations、actions 和 getters。注册 Vuex Store:
main.js 文件中,我们通过 app.use(store) 将 Vuex store 注册到 Vue 应用中。在组件中使用 Vuex:
{{ count }} 来显示 state 中的 count 值。@click="increment" 绑定按钮点击事件来触发 actions 中的 increment 方法。<script> 部分,我们使用 mapState 和 mapActions 辅助函数将 Vuex 的 state 和 actions 映射到组件的 computed 和 methods 中。这样,你就可以在 Vue 3 项目中成功集成并使用 Vuex 进行状态管理了。
下一篇:vue等待几秒
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站