安装
如果在建立项目时没有选择使用vuex那么就npm安装
npm install vuex
定义一个store文件夹,里面有index.js和module文件夹
strore/index.js
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex);
import Product from "./module/Product"
import App from "./module/app"
export default new Vuex.Store({
strict: true,
state: {
},
mutations: {
},
actions: {
},
modules: {
App,
Product,
}
})
store/module/app.js
import { getStoreInfo,getHomePageData } from '@/api/api.js';
export default {
state: {
StoreInfo: {
"StoreName": "鹿城区站前花牧春花店",
"CreditCode": "92330302MA2C5HU30R",
},
HomePageData: {},
},
getters: {
/**
* 返回 首屏列表 数据
*/
GHomePageData(state) {
return state.HomePageData;
},
},
actions: {
/**
* 获取 首屏列表 数据
*/
AHomePageData(ctx, query) {
return new Promise((resolve, reject) => {
getHomePageData(query).then(({data}) => {
ctx.commit(MHomePageData,data);
resolve();
}).catch(error => {
ctx.commit(MHomePageData, {});
reject(error);
});
});
},
},
mutations: {
/**
* 填充 首屏幕列表 数据
*/
MHomePageData(state, access) {
state.HomePageData = access;
},
}
};
main.js
import store from './store'
Vue.prototype.$store = store;
其他页面使用
this.$store.store.StoreInfo.StoreName
更多
mapState使用
当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性
import { mapState } from 'Vuex'
computed: mapState({
count: 'count',//第一种写法
sex: (state) => state.sex,//第二种写法
from: function (state) {//第三种写法,this指向vue实例
return this.str + ':' + state.from
},
num: function () {//第四种写法
return '测试' + this.str
}
})
state里面的数据在使用的时候,一般是挂在computed里面的,因为如果你挂在data上面, 只会赋值一次,不会跟着vuex里面的变化而同步变化,当然也可以通过watch $store去解决这个问题