适合vue新手的vuex使用案例

156 阅读1分钟

本文以 cityId 为例

1、搭建目录结构

src/store/index.js 文件

import Vue from "vue";
import Vuex from "vuex";
import task from "./modules/city.js";

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    city
  }
});

export default store;

src/store/modules/city.js 文件

export default {
  state: {
    cityId: "",
  },
  getters: {
    cityId: state => state.cityId
  }
  mutations: {
    SET_CITY_ID(state, { cityId }) {
      state.cityId = cityId;
    },
  },
  actions: {
    changeCityId({ commit }, { cityId }) {
      commit("SET_CITY_ID", { cityId });
      return Promise.resolve();
    }
  },
};

2、使用 cityId

src/pages/test01.vue

import { mapGetters, mapActions } from "vuex";

export default {
    data() {},
    computed: {
        ...mapGetters({
            cityId: "cityId"
        })
     },
     methods: {
         ...mapActions({
             changeGlobalCityId: "changeCityId"
         }),
         // 某个方法中提交更改 cityId
         fn(rowData) {
             this.changeGlobalProcDefKey({ cityId: rowData.cityId });
         }
     }
}

src/pages/test02.vue 这个页面只是想单纯的使用cityId,没有更改需求

import { mapGetters } from "vuex";

export default {
    data() {},
    computed: {
        ...mapGetters({
            cityId: "cityId"
        })
     },
     created() {
         console.log(this.cityId, "获取到 cityId 了哦~~~");
     },
}

好了~ 就是这么简单,快去造轮子吧~~