vuex学习心得
cnpm i vuex –save 安装vuex
main.js 引入
import Vuex from “vuex”
Vue.use(Vuex)
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 30 31 32 33 34 35 36
| const app = { state: { count: 0 }, getters: { myCount(state) { return `当前值是${state.count}` } }, mutations: { increment(state, n) { state.count += n }, decrement(state, n) { state.count -= n }
}, actions: { myIncrease(content, obj) { content.commit("increment", 2) console.log(obj); }, myDecrease(content) { content.commit("decrement", 3) }, } } export default app
|
挂载到Vue实例上
1 2 3 4 5 6 7
| new Vue({ el: '#app', router, components: { App }, template: '<App/>', store })
|
在APP.vue
1 2 3 4 5 6 7 8 9 10 11 12 13
| import {mapState} from "vuex" export default { name: "App", data() { return {}; }, computed:{ ...mapState(["count"]) }, }, };
|
在应用的页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import { mapMutations, mapActions } from "vuex"; export default { name: "HelloWorld", data() { return { msg: "Welcome to Your Vue.js App", }; }, methods: { ...mapMutations(["increment", "decrement"]), ...mapActions(["myIncrease", "myDecrease"]), increment() { this.myIncrease(); console.log(this.myIncrease); }, decrement() { this.myDecrease(); }, }, };
|
一般来说,会新建一个vuex专门的状态管理文件
index.js负责引入其他状态管理模块
1 2 3 4 5 6 7 8 9 10 11 12
| import Vue from 'vue' import Vuex from "vuex" import app from "./app" import user from "./user" Vue.use(Vuex); const store = new Vuex.Store({ modules: { app, user } }) export default store
|
…mapState 是store里state的映射
…mapState([‘num’])=>state[num]
…mapGetters是store里getters的映射
…mapGetters([‘num’])=>getNum,
两者都写在computed里面
…mapMutations和…mapActions写在methods里面
MUTATION_TYPE
将mutations的方法全部 放到MUTATIONS_TYPE里
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| export const MUTATIONS_TYPE = { INCREASE: "increase", DECREASE: "decrease" } export default {
[MUTATIONS_TYPE.INCREASE](state, payload) { state.num += payload ? payload : 1 }, [MUTATIONS_TYPE.DECREASE](state) { state.num-- }
}
|
mutations.js
1 2 3 4 5 6 7 8 9 10 11
| export default {
// 加一的函数 increase(state, payload) { state.num += payload ? payload : 1 }, decrease(state) { state.num-- }
}
|
调用
import { MUTATIONS_TYPE } from “../store/mutations_type”;
…mapMutations([MUTATIONS_TYPE.INCREASE]),
如果要获取stroe文件下组件的值,在调用的组件内加上computed属性返回即可