javascript - 当数据数组插入新元素时如何更新子组件?

标签 javascript arrays vue.js vuejs2 vue-component

我有一个 vue.js 子组件,其中包含一个名为 messages 的数据数组。在数组中插入新元素时如何更新 DOM。

这是我的代码的简化片段:

<template>
  <q-item v-for="(msg, i) in messages" :key="i" >
    <!-- q-item is a custom component of quasar framework -->
    <!-- some code here related to msg -->
  </q-item>
<template/>

<script>
  export default {
  data () {
    return {
      messages: []
    }
  },
  methods: {
    submitMessage () {
      // submit the formData
      this.submitFormData({url: '/messages/new', formData})
        .then((message) => {
          this.messages.push(message)
        })
      },
    }
  }
}
<script/>

使用 vue devtools 我可以看到消息数组已更新,但我无法根据它更新 DOM。

注意这是一个子组件,而不是 vue 实例($forceUpdate 不起作用)

最佳答案

你应该这样做:

<template>
    <q-item v-for="(msg, i) in messages" :key="i" >
    <!-- q-item is a custom component of quasar framework -->
    <!-- some code here related to msg -->
    </q-item>
<template/>

<script>
export default {
    data () {
        return {
            messages: []
        }
    },
    methods: {
        submitMessage () {
        // submit the formData
        this.submitFormData({url: '/messages/new', formData})
            .then((message) => {
            this.messages.push(message)
            })
        }
    }
</script>

vue 最好的部分之一是,它动态更新 gui 元素(组件),您的错误是 methods: {} 位于 data() {}.

希望对您有所帮助。

关于javascript - 当数据数组插入新元素时如何更新子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46487731/

相关文章:

javascript - 在 javascript 中处理嵌套 promise 树的最快方法?

c - 如何在 C 中创建保存静态数组的动态数组?

javascript - 将值从 Promise 传递给变量

javascript - 添加指向数据表的链接以获取更多信息

javascript - Angular 5 嵌套数组

python - 从变量中的索引获取 numpy 数组中的值

php - 将文件内容转换为 JavaScript 数组

mongodb - 在nuxt中使用mongodb

javascript - 如何让vue每天只显示一次弹出窗口

javascript - AngularJS 注入(inject)器执行时出错