vue中使用socket.io后怎么在sockets获取到后台数据后,改变store中的值?

如下设置后,能够连接上本地服务器

import store from './store'
import VueSocketio from 'vue-socket.io';
import socketio from 'socket.io-client';
Vue.use(VueSocketio, socketio('http://127.0.0.1:7777/'),store);

下一步就是获取后台数据后赋值

sockets: {
    getData: (data) => {
      console.log(this.$store); 
    }
}   

打印出undefined 。 其他地方正常使用store
试过在mounted中打印this是 VueComponent {_uid: 4, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}
在sockets中打印this是{a: {…}}
a: {name: "Home", components: {…}, sockets: {…}, mounted: ƒ, methods: {…} , 是当前页面的信息。
该怎么办呢

阅读 5.9k
1 个回答

this.$storeVuex为方便调用而自动注入到实例中每个子组件的store对象,其实它就是你store.js中暴露出来的那个store
在非vue实例组件中调用直接引入即可

import store from './store'

export default {
  sockets: {
    getData: (data) => {
      //store.state...
      //store.commit('')
      console.log(store);
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题