简体   繁体   English

反应式 Vue 组件不更新数据更改

[英]reactive Vue component not updating on data change

I'm new to Vue and trying to display a list of "notes" which update when a button is hit (I've just hardcoded the value to add for now).我是 Vue 的新手,并试图显示一个“注释”列表,当按下按钮时会更新(我刚刚硬编码了要添加的值)。 The trouble is that after I add a new item to the array, this isn't updated in the UI.问题是,在我向数组添加一个新项目后,它并没有在 UI 中更新。 I'm using Vue3 and The:key I'm using is unique.我正在使用 Vue3,而我使用的 The:key 是独一无二的。 Other "widgets" I've made have worked as expected but they got data from an api response.我制作的其他“小部件”按预期工作,但他们从 api 响应中获取数据。 Is it related maybe to the async/await aspect of dealing with API responses compared with just appending/pushing to the data array?与仅附加/推送到数据数组相比,它可能与处理 API 响应的异步/等待方面有关吗?

<template>
 <Widget class="notes" :style="style" @load="showNotes()">
<h3>Notes</h3>
<p v-for="item in data" :key="item.id">{{ item.note }}</p>

<button @click="addNote()">Add</button>
</Widget>
</template>

<script>
import Widget from "./Widget.vue";

export default {
  name: "Notes",
  props: {
    widgetWidth: Number,
  },
  computed: {
    style() {
      return "max-width: " + this.widgetWidth + "px";
    },
  },
  data() {
    return {
      notes: undefined,
    };
  },

  methods: {
    addNote() {
      var x;
      if (!this.data) {
        this.data = [];
        x = 0;
      } else {
        x = this.data.length;
        console.log(x);
      }
      this.data.push({ id: x, note: "another" });
      console.log(this.data);
    },
    showNotes() {
      this.data = [{ id: 0, note: "init" }];
    },
  },
  beforeMount() {
    this.showNotes();
  },
  components: { Widget },
};
</script>

<style scoped>
.notes {
  min-width: 100px;
  word-wrap: break-word;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.notes > * {
  flex-grow: 1;
}
</style>

That's happening because you modify the data property and there is no data property, it's notes property, Also, you don't need the @load event, or beforeMount event to initialize the notes property.发生这种情况是因为您修改了data属性并且没有data属性,它是notes属性,此外,您不需要 @load 事件或 beforeMount 事件来初始化 notes 属性。

This working example这个工作示例

Create a computed property called notes that returns the notes property in your data object.创建一个名为 notes 的计算属性,该属性返回数据 object 中的 notes 属性。 In your v-for use item in notes.在你的 v-for use 项目的注释中。 When you click the button the notes in your data object gets updated.当您单击按钮时,数据 object 中的注释会更新。 The computed property detects the change and updates the ui计算属性检测更改并更新 ui

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM