Vuex使用流程

时间:2021-02-23
本文章向大家介绍Vuex使用流程,主要包括Vuex使用流程使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.可以devDependencies安装:npm install vuex -D

"vuex": "^3.6.2"
2.创建store文件src/store/index.js或者src/store.js
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

import travel from "./modules/travel";
import goods from "./modules/goods";

import * as api from "../api";

export default new Vuex.Store({
    state: {
        pubInfo: [],
    },
    mutations: {
        SET_PUB_INFO(state, pubInfo) {
            state.pubInfo = pubInfo;
        },
    },
    actions: {
        getPubInfo({ commit }) {
            console.log("getPubInfo");
            return api
                .requestPubInfo()
                .then((res) => {
                    console.log("getPubInfo-success");
                    if (res.rtnCode === "success") {
                        commit("SET_PUB_INFO", res.data);
                        return Promise.resolve(res.data);
                    } else {
                        return Promise.reject(null);
                    }
                })
                .catch((error) => {
                    console.log("getPubInfo-error");
                    return Promise.reject(error);
                });
        },
    },
    modules: {
        travel,
        goods,
    },
});

  引入并使用vuex,实例化一个store对象并抛出,上面是一个例子。

3.引入到src/main.js,并注入到Vue实例:

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

import "amfe-flexible/index"; //设置font-size为 deviceWidth / 10,配合postcss-adaptive-exclude使用
// import 'amfe-flexible'

import * as api from "./api";
Vue.prototype.$api = api;
Vue.config.productionTip = false;

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

  

4.使用:

import { mapState } from "vuex";

//.....
computed: {
        ...mapState({
            pubInfo: (state) => state.pubInfo,
        }),
    },

  或者:

created() {
        this.$store
            .dispatch("travel/getTravel", "test-params")
            .then((res) => {
                console.log("res:", res);
                if ("success" == res.rtnCode) {
                    this.travel = res.data;
                }
            })
            .catch((e) => {
                console.log("e:", e);
            });
    },

  

原文地址:https://www.cnblogs.com/fengyouqi/p/14437547.html