Vuex 3.4.0 版本 使用Vuex 以及 持久化 Vuex

1,459 阅读1分钟
  • 安装命令的方式 分别为 cnpmnpmyarn
  • 普遍情况用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开启命名空间 当页面越来越多 越来越臃肿
  // vuex模块拆分后 命名空间尤为重要!
  namespaced:true
};
  • 在vue 的 store目录下 index.js文件中进行拆分引入
import Vue from "vue";
import Vuex from "vuex";
// 这里引入 store模块文件
import store from "./module/store";
// 这里引入了vux持久化
import createPersistedState from "vuex-persistedstate"
Vue.use(Vuex);

export default new Vuex.Store({
  // 这里结构封装的store
  ...store,
  modules: {},
  // 这里引入vuex持久化
  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 {
    // 使用vuex中state数据 需要在计算属性中
    // 运用扩展符进行扩展
    computed: {
        ...mapState({
          count: (state) => state.count,
        }),
    },
    // 如果更改的是Actions数据 需要在methods中进行扩展使用
    methods: {
        //传递参数可以用一个方法add调用和接收
        ...mapActions({
          // add 映射为 this.add() 
          add:'incrementAction'
        }),
            
            // 上下方法根据需求选择
            
        // 若不传递参数 可以使用 
        ...mapActions([
            'incrementAction'
        ]),
        
        // 这里事件是通过底层原型获取到的store方法进行传参和修改
        commitNumber() {
          this.$store.commit('increment', 10)
        },
    },
};
</script>