Template node - How can I get node red data from Vue Components [Resolve]

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)
    })

But how can i do the same from a Vue Components ? (for example in : Text ui-template | Node-RED Dashboard 2.0)

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)
            })            
        },
1 Like

Pleased to see you got there yourself, hope youre enjoying working with Dashboard 2.0

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)…

Maybe I’m missing something - did you declare/initialize items (i.e. var this.items = []; )?

Thank you ! It’s working now :slight_smile:

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')
})
1 Like