vuex的官网文档:https://vuex.vuejs.org/zh/installation.html
简单的vuex列子:https://www.cnblogs.com/wisewrong/p/6344390.html
第一步安装:(二选一)
npm install vuex@next --save
npm install vuex -S
第二步引用:
在main.js中
import store from './store'
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
第三步创建存放的js,
第四步存放需要的字段
1.先将需要的字段在state中定义
2.
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
online:new Map()//定义的字段
// online:{}
},
mutations: { //更新状态
increment (state,online) { //state是上面的state,online为传过来的
console.log(online)
var tempMap=new Map()
online.forEach(element => {
tempMap.set(element.id,element.online)
});
state.online=tempMap //传递到各个页面的是这个
}
},
actions:{},
modules,
getters,
})
export default store
3.在全局方法中将需要的参数更新到store中的increment 中
getOnlineList(){
setInterval(() => {
this.$axios.get("*******").then((res) => {
this.$store.commit('increment',res.data)
});
}, 50000);
}
4.在getter页面中
5.其他页面接收到实时更新数据
(1)使用getter
<div>
{{online1.get('4568789500')}}
</div>
import { mapGetters } from 'vuex'
computed:{
...mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
online1: 'online'
}),
}
(2)直接调用
computed:{
online1(){
return this.$store.state.online
}
}