在 Vue2 中使用 Vuex2 的步骤
1.安装 Vuex:
npm install vuex@2 --save
2.创建一个 store.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: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
}
},
getters: {
getCount: state => {
return state.count;
}
}
});
3.在 main.js 文件中引入 store,并将其添加到 Vue 实例中:
import Vue from 'vue';
import App from './App.vue';
import store from './store';
new Vue({
el: '#app',
store,
render: h => h(App)
});
4.在组件中使用 store 的状态和方法:
<template>
<div>
<p>Count: {{ $store.state.count }}</p>
<p>Count: {{ $store.state.num }}-{{ num }}</p>
<p>Double Count: {{ $store.getters.doubleCount }}</p>
<button @click="$store.dispatch('increment')">Increment</button>
<button @click="decrement">Decrement</button>
<hr>
<p>Count: {{ count }}</p>
<p>Double Count: {{ doubleCount }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapActions } from 'vuex';
export default {
computed: {
...mapState({
count: state => state.count,
num: state => state.num,
}),
...mapGetters({
doubleCount: 'doubleCount',
}),
},
methods: {
...mapActions({
increment: 'increment',
decrement: 'decrement',
}),
},
};
</script>
<style>
</style>