【问题标题】:NUXTJS: How do I update data() variable from client side javascriptNUXTJS:如何从客户端 javascript 更新 data() 变量
【发布时间】:2021-10-30 12:56:54
【问题描述】:
data() {
  const ports = [
    {
      subtitle: "PORT 1",
      title: "COM8",
    },
    {
      subtitle: "PORT 2",
      title: "COM11",
    },
  ];

  return {
    ports,
  };
},

我有一个名为 ports 的服务器端变量。我想更新/添加项目并希望 vue 渲染器响应式更新它。

下面的javascript会起作用吗?

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

EDIT1:我想明确表示我是从客户端浏览器调用上面的脚本块。

EDIT2: 遵循 Kissu 的回答,问题是我收到来自浏览器客户端 javascript 的 "Uncaught Reference Error: addOne is undefined" 错误

例如

我所做的只是从浏览器客户端 javascript 调用 addOne()

例如

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

EDIT3:根据@kissu 要求

//websocket running on browser

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

【问题讨论】:

  • 这段代码在哪里? ws.on("message", function (msg) {
  • 浏览器客户端。正在浏览网站的用户。
  • 这并不意味着什么。 Nuxt(及其背后的 Vue)也是一个客户端 JS 框架。
  • 我不明白if browser client side will not work,为什么有些客户端代码不能工作? vue methods via API rest call,您不会通过调用某些 API 调用来调用客户端 Vue 方法。它甚至意味着什么?这两件事完全不相关。您可以使用香草fetch 方法或一些axios 是的。
  • Axios 可以在客户端、服务器上运行,因此可以在 Vue/Nuxt 上下文中运行。

标签: javascript nuxt.js vuetify.js


【解决方案1】:

在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>

【讨论】:

  • 如何通过javascript调用它?不是来自按钮点击,而是某种形式的事件,如 websocket?
  • @agentpx 在 websocket 上使用回调函数并调用方法。
  • 是的,我有很多这样的方法,但我从来没有想到要调用它而不是直接更新变量。我会试试这个。我是 nuxtjs 的新手。谢谢。
  • 我收到 Uncaught ReferenceError: addOne is not defined.
  • @agentpx 没有server side component 可以这么说。为了利用反应性,通过一些生命周期钩子在适当的上下文中使用 websockets 并相应地跟踪它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2011-10-14
  • 2015-03-03
  • 2017-04-04
  • 1970-01-01
相关资源
最近更新 更多