agentpx
agentpx

Reputation: 1081

NUXTJS: How do I update data() variable from client side javascript

data() {
  const ports = [
    {
      subtitle: "PORT 1",
      title: "COM8",
    },
    {
      subtitle: "PORT 2",
      title: "COM11",
    },
  ];

  return {
    ports,
  };
},

I have a server side variable named ports. I want to update/add items to it and hope vue renderer updates it reactively.

will javascript below would work?

<script>
  this.ports.push({ title: devicePort, subtitle: deviceName });
</script>

EDIT1: I'd like to make it clear that I am calling script block above from client side browser.

EDIT2: Followed kissu's answer, problem is I'm getting "Uncaught Reference Error: addOne is undefined" error from browser client javascript

e.g.

What I did is just call addOne() from browser client javascript

e.g.

setTimeout(function( {
  addOne(); //undefined
},100)

EDIT3: as per @kissu request

//websocket running on browser

ws.on("message", function (msg) {
  addOne(); 
  // **"Uncaught Reference Error: addOne is undefined"**
}

Upvotes: 1

Views: 1363

Answers (1)

kissu
kissu

Reputation: 46769

This is how it should be written in Vue2

<template>
  <div>
    <pre>{{ array }}</pre>
    <button @click="addOne">Add one object to the array</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      array: [
        {
          subtitle: 'PORT 1',
          title: 'COM8',
        },
        {
          subtitle: 'PORT 2',
          title: 'COM11',
        },
      ],
    }
  },
  methods: {
    addOne() {
      this.array.push({ title: '3000', subtitle: 'Samsung' })

      // the one below is a bit more bulletproof, more info here: https://vuejs.org/v2/guide/reactivity.html#For-Arrays
      // this.$set(this.array, this.array.length, { title: '3000', subtitle: 'Samsung' })
    },
  },
}
</script>

Upvotes: 1

Related Questions