项目背景
websocket长连接 根据指示进行四个页面之间的跳转,在各页面执行相应的逻辑处理。
项目搭建结构如下所示:
解决方案
在四个页面外面写个父页面,router路径如下所示:
vuex
\src\store\mutations.js
//存储到vuex里面
[WEBSOCKETDATA](state,socketdata){ state.socketData=null;//vue监听不到数组的改变 所以清空重置一下就好咯 state.socketData=socketdata }
\src\store\getters.js
export default { getterSocketData (state) { return state.socketData } }
\src\store\index.js
import Vue from 'vue' import Vuex from 'vuex' import mutations from './mutations' import getters from './getters'
Vue.use(Vuex)
const state = { socketData:{},//websocket数据 } export default new Vuex.Store({ state, mutations, getters })
\src\components\index.vue
父页面
import {mapMutations,mapState} from 'vuex' export default { computed:{ ...mapState([ 'socketData', ]) }, data(){ return{ skip:'2', webdata:{ "current_item": "111", "show_item": 'false', "cart_item_list": [],"totalPrice":7.5,"delIndexList":[],'addList':[] }, } }, mounted(){ // this.initWebsocket() var addList=[{"sku":"1","num":"2","price":3.5,"name":'苹果0'}]; var delIndexList=[]; this.webdata.addList=addList; this.webdata.delIndexList=delIndexList; this.websocket_data(this.webdata) console.log("index1--------------------") console.log(this.socketData); setTimeout(()=>{//定时器为了模拟websocket发送数据 var addList=[{"sku":"1","num":"2","price":3.5,"name":'苹果11'}]; var delIndexList=[0]; this.webdata.addList=addList; this.webdata.delIndexList=delIndexList; this.$store.commit("websocket_data",this.webdata)//必须写 要不然getter拿不到改变之后的数据 console.log("index--------------------"); console.log(this.socketData); },1000); }, }
src\components\shoppingCart.vue
子页面 根据websocket传来的数据进行逻辑操作
import {mapState,mapMutations,mapGetters} from 'vuex'; export default { data(){ return{ prolength:0, defaultImg: 'this.src="' + require('../assets/defaultImg.png') + '"', productinfos: { "current_item": "111", "show_item": 'false', "cart_item_list": [],"totalPrice":7.5,"delIndexList":[],'addList':[] }, MyMar:'', } }, computed: {//监听socketData的变化 做页面处理 ...mapState([ 'socketData', ]), ...mapGetters([ 'getterSocketData', ]) }, watch:{ getterSocketData(message){//message 就是socketData console.log(message);//根据数据指示 进行逻辑操作 ........................ } } }
以上这篇vuex提交state&&实时监听state数据的改变方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持找一找教程网。