Hi !
Thank you very much for your work in Dashboard 2.0 !
Here is my question…
I can use this code in custom widgets
// Subscribe to the incoming msg's
this.$socket.on('msg-input:' + this.id, function(msg) {
// do stuff with the message
alert('message received: ' + msg.payload)
})
Sorry, i’ve found a solution by subscribing in the mounted() function
mounted() {
// code here when the component is first loaded
// Subscribe to the incoming msg's
this.$socket.on('msg-input:' + this.id, function(msg) {
// do stuff with the message
alert('message received: ' + msg.payload)
})
},
Thank you !
Now, if i want to use data() values in mounted() function, i’ve a
Uncaught (in promise) TypeError: this.items is undefined
Complete code
<script>
export default {
data() {
return {
items: ['foo', 'bar','fizz', 'buzz', 'test'],
value: 'bar',
}
},
mounted() {
// code here when the component is first loaded
// Subscribe to the incoming msg's
this.$socket.on('msg-input:' + this.id, function(msg) {
// do stuff with the message
this.items.push('new')
})
},
}
</script>
Sometimes, i’m asking myself if i’ve to use template (more flexibility) or nodes (easier)…
Just to point out the specific issue here - your definition of the callback and use of function creates a new this scope. That means that this. then references the function, not the Vue component inside that function block.
You have two options:
1. Anonymous Function
this.$socket.on('msg-input:' + this.id, (msg) => {
// do stuff with the message
this.items.push('new')
})
at which point this will maintain it’s reference to the Vue component
2. vue = this
You can maintain a reference to the parent this by doing:
const vue = this
vue.$socket.on('msg-input:' + vue.id, function (msg) {
// do stuff with the message
vue.items.push('new')
})