Faizuddin Mohammed
Faizuddin Mohammed

Reputation: 4328

Watching Objects with Sockets in VueJS?

I'm using Sockets to receive data from a remote server.

I'm using the following an app Vue component:

let app = {
 name: 'app',
 data: {
  dataStore: {}
 },
 mounted () {
  var vm = this;
  socket.on('data-receive', (data) => { //data = {user: 'myUser' value: 45}
   vm.dataStore[data.user] = data.value // also tried Vue.set(vm.dataStore, data.user, data.value)
   console.log(vm.dataStore)
  })
 }

The weird thing is that the console logs dataStore properly as expected. Even the Vue Developer Tools show the proper data stored in dataStore. But, the dataStore is rendered as {} on the following HTML

<app>
{{dataStore}}
</app>

And here's what's rendered:

{}

Is there anyway to force re-render?

Upvotes: 1

Views: 833

Answers (1)

Saurabh
Saurabh

Reputation: 73649

try following:

mounted () {
  var vm = this;
  socket.on('data-receive', (data) => { 
   Vue.set(vm.dataStore, 'user', data.user)   // or vm.$set(...)
   Vue.set(vm.dataStore, 'value', data. value)
   console.log(vm.dataStore)
  })
}

As described in the documentation:

Vue cannot detect property addition or deletion. Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the data object in order for Vue to convert it and make it reactive

One can add reactive properties to a nested object using the Vue.set(object, key, value) method:

Edited:

As suggested in comment, as the code is in sockets, probably this is happening outside vue instance and using forceUpdate renders updated variable in HTML.

Upvotes: 1

Related Questions