vuex3使用记录,适配vue2项目

168 阅读1分钟

1. 安装依赖

npm i vuex@3.1.0

2. src文件夹下新建store文件夹

store文件夹下新建index.js文件,modules文件夹

//index.js文件
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
//把modules文件底下的模块遍历进来
const modulesFiles = require.context("./modules", true, /\.js$/);
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
  const value = modulesFiles(modulePath);
  modules[moduleName] = value.default;
  return modules;
}, {});
export default new Vuex.Store({
  modules,
});

modules文件夹下新建counter.js文件

//counter.js
const state = {
  count: 0,
};
const mutations = {
  increment(state) {
    state.count++;
  },
  decrement(state) {
    state.count--;
  },
};
const actions = {
  incrementAsync({ commit }) {
    setTimeout(() => {
      commit("increment");
    }, 1000);
  },
};
const getters = {
  getCount: (state) => state.count,
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};

3. main.js引入store

//main.js
import Vue from "vue";
import App from "./App.vue";
import store from "./store";
Vue.config.productionTip = false;

new Vue({
  render: (h) => h(App),
  store,
}).$mount("#app");

4. vue文件中使用store

//app.vue
<template>
  <div id="app">
    <p>{{ count }}</p>
    <p>{{ doubleCount }}</p>
    <button @click="increment">count++</button>
    <button @click="decrement">count--</button>
    <button @click="incrementAsync">incrementAsync++</button>
  </div>
</template>

<script>
import { mapState, mapMutations, mapGetters, mapActions } from "vuex";

export default {
  name: "App",
  computed: {
    //获取state中数据
    //方式1
    ...mapState({
      count: (state) => state.counter.count,
    }),
    //方式2
    ...mapState("counter", ["count"]),

    //mapGetters获取的两种方式
    //1
    ...mapGetters("counter", ["doubleCount"]),
    //2.别名状态下
    ...mapGetters({
      doubleCount: "counter/doubleCount",
    }),
  },
  methods: {
    //组件中调用命名空间模块中的Mutations
    //方式1
    decrement() {
      this.$store.commit("counter/decrement");
    },
    //方式2
    ...mapMutations("counter", ["increment,decrement"]),
    //方式3
    ...mapMutations({
      increment: "counter/increment",
      decrement: "counter/decrement",
    }),

    //组件中调用命名空间模块中的的actions
    //1.
    incrementAsync() {
      this.$store.dispatch("counter/incrementAsync");
    },
    //2.
    ...mapActions("counter", ["incrementAsync"]),
    //3.别名状态下
    ...mapActions({
      incrementAsync: "counter/incrementAsync",
    }),
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>