- 安装命令的方式 分别为
cnpm
或 npm
或 yarn
- 普遍情况用npm
- yarn虽然安装更快捷,但需要下载,如有兴趣可查资料
npm install vuex-persistedstate --save
- 在store目录中封装一个store.js模块文件
- 包含state、mutations、actions
export default {
state: {
userName: "hello",
count: 20,
},
mutations: {
setState(state, val) {
state.count = val;
},
increment(state, v) {
state.count += v;
},
},
actions: {
incrementAction(context,val){
context.commit('increment',val)
}
},
namespaced:true
};
- 在vue 的 store目录下 index.js文件中进行拆分引入
import Vue from "vue";
import Vuex from "vuex";
import store from "./module/store";
import createPersistedState from "vuex-persistedstate"
Vue.use(Vuex);
export default new Vuex.Store({
...store,
modules: {},
plugins: [
createPersistedState({
storage: window.sessionStorage,
}),
],
});
- Home.vue组件 template进行事件绑定
- 这里的
<button @click="add(30)">mutations</button>
代表点击count增加30
<template>
<div>
<p>vuex</p>
<button @click="add(30)">mutations</button>
<p>
{{ count }}
</p>
<button @click="commitNumber">mutations</button>
</div>
</template>
- 引入vuex中定义的 state 以及 actions 异步
<script>
import { mapState ,mapActions} from "vuex";
export default {
computed: {
...mapState({
count: (state) => state.count,
}),
},
methods: {
...mapActions({
add:'incrementAction'
}),
...mapActions([
'incrementAction'
]),
commitNumber() {
this.$store.commit('increment', 10)
},
},
};
</script>