先安装vuex
npm install vuex --save
在根目录新建store
文件夹,然后在store
文件夹中新建index.js
以及modules
文件夹,modules
文件夹下新建base.js
,这个命名是随意的,不需要一定是base
,我在里面只是想存放一个屏幕大小的变量,所以取名为base.js
。
在index.js
中写入以下内容,index.js
相当于vue
中的main.js
,就是全局变量的一个入口文件,记录使用了哪些模块,新建的模块都要在这里引入注册
import Vue from 'vue';
import Vuex from 'vuex';
import base from './modules/base'
Vue.use(Vuex);
const store = () =>new Vuex.Store({
modules: {
base,
}
});
export default store;
在base.js
中写入以下内容,命名空间相当于定义了使用全局变量的时候要指定模块名,既然都已经模块化使用了,那自然肯定要加命名空间
const state = ({ //state里面存放的是变量,如果你要注册全局变量,写这里
isPc:true,
showImg:true
});
/*const getters = { //getters相当于是state的计算属性,如果你需要将变量的值进行计算,然后输出,写这里
include: (state) => (val) => {
return state.list.indexOf(val) > -1;
}
}
;*/
const mutations = { //修改store中的变量的方法,如果你要改变变量的值,就写这里
SET_isPc(state, value) {
state.isPc = value;
},
SET_showImg(state, value) {
state.showImg = value;
}
};
/*const actions = { //actions提交的是mutations,相当于就是改变变量的方法的重写,但是,actions是可以进行异步操作的,即相当于promise中的then和catch
async setIsPc({state, commit}, val) {
commit('SET_isPc', val);
}
};*/
export default {
namespaced:true, //命名空间
state, //这里你用到了哪几个属性就写哪几个,不需要的可以注释掉
// getters,
// actions,
mutations
};
在main.js
中引入store
import Vue from 'vue'
import App from './App'
import router from './router'
import store from "./store/index"
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
router,
render: h => h(App)
});
1.简单访问使用
如果要访问上面的isPc
变量,代码如下
this.$store.state.base.isPc;
//调用getters就是state换成getters,然后isPc换成相应的getters的名字
如果要访问上面的SET_isPc
的mutation
,代码如下
this.$store.commit('/base/SET_isPc',false);
//调用action就是commit换成dispatch,然后SET_isPc换成相应的action的名字
2.模块化访问使用
在平常组件中的使用,首先引用你需要的变量或者是改变变量的方法或者是计算属性
import {mapState,mapMutations}from 'vuex'
//如果引用actions就是mapActions
//如果引用getters就是mapGetters
state
和getters
写computed
计算属性里面
computed:{
...mapState('base', {
isPc: state => state.isPc, //变量的名字
})
},
mutations
和actions
写methods
方法里面,base
就是你引用的base.js
methods:{
...mapMutations('base', [
'SET_isPc', //mutations的名字
'SET_showImg' //mutations的名字
]),
}