1.入口文件main.js
import Vue from 'vue'
import Layout from './layout'
import router from './router'
// 引入vuex
import store from './store/store
vue实例中
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { Layout },
template: '<Layout/>'
})
store文件下创建store.js
store.js中设置
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
pjtnews: 0,
count: 1
}
const mutations = {
add(state) {
state.count += 1;
},
reduce(state) {
state.count -= 1;
}
}
export default new Vuex.Store({
state,
mutations
});
以上参考 :vue项目中如何引入vuex__cris的博客-CSDN博客_vuex引入
———————————— 分割 ——————————————
存储全局变量
import { mapActions, mapGetters } from 'vuex'
this.$store.commit("hotline/setUserInfo", this.hotLineData);
//hotline: 是src/store文件的modules中的js文件 , this.hotLineData是该文件中定义的函数
//即第一个参数为方法,第二个参数为数据
src/store/modules/hotline.js文件如下,全局数据通过调用mutations中的方法存放在state对象中,
/**
* 存放 ** 数据
* **/
// initial state
const state = {
userInfo: [],
nowInfo: {}
}
// getters
const getters = {}
// actions
const actions = {}
// mutations
const mutations = {
setUserInfo(state, userInfo) { //设置参数
state.userInfo = userInfo;
},
setNowInfo(state, nowInfo) { //设置参数
state.nowInfo = nowInfo;
}
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
全局变量的拿取使用:
在其他vue文件的计算属性下拿到,就可直接this.userInfo 、this.nowInfo,调用了
import { mapState, mapActions } from "vuex"
computed: {
...mapState({
userInfo: (state) => state.hotline.userInfo,
nowInfo: (state) => state.hotline.nowInfo,
}),
},
Vuex官方文档:开始 | Vuex