Vue3 - 更新的数组不会自动呈现

Vue3 - updated array not rendered automatically

刚接触 Vue,我不知道如何自动呈现更新后的数组。

我有一个非常基本的页面,包括一个输入和一个按钮。单击该按钮后,数据将通过我的服务器保存在 MongoDB 中。

在表格的正下方,我正在显示从 Mongo 获取的数据。

但是,当我创建新项目时,我需要重新加载页面才能看到更新后的列表。我应该如何继续查看 table 更新“实时”?

这是我的 Vue 代码:

<template>
  <div class="home">
    <h1>Hello</h1>
    <form submit.prevent="">
      <input v-model="newItem" type="text">
    </form>
    <button @click="createItem">Create</button>
    <div>
      <table>
        <tr>
          <th>Name</th>
        </tr>
        <tr v-for="(item, index) of items" :key="index">
          <td>{{ item.name }}</td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
import CrudService from '../services/crud.service';
import { ref } from 'vue';

export default {
  data(){
    return{
      newItem: '',
      items: [],
    }
  },

  async mounted(){
    await this.readItems();
  },

  methods: {
    async readItems(){
      const results = await CrudService.readItems();
      results.data.forEach(element => {
        ref(this.items.push(element));
      });
    },

    async createItem(){
      await CrudService.createItem({ item: this.newItem });
    }
  }
}
</script>

像下面的片段一样尝试(取消对 api 调用的注释):

new Vue({
  el: "#demo",
  data(){
    return{
      newItem: {
        name: ''
      },
      items: [],
    }
  },

  async mounted(){
    await this.readItems();
  },

  methods: {
    async readItems(){
      // const results = await CrudService.readItems();
      const results = [{name:1},{name:2},{name:3}]
      this.items = results
    },

    createItem(){
     // await CrudService.createItem({ item: this.newItem });
      this.items.push({...this.newItem})
      this.newItem.name = ''
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div class="home">
    <h1>Hello</h1>
    <form submit.prevent="">
      <input v-model="newItem.name" type="text">
    </form>
    <button @click="createItem">Create</button>
    <div>
      <table>
        <tr>
          <th>Name</th>
        </tr>
        <tr v-for="(item, index) of items" :key="index">
          <td>{{ item.name }}</td>
        </tr>
      </table>
    </div>
  </div>
</div>

您可以在创建项目后调用 readitems() 方法来更新您的视图而无需刷新。

<script>
import CrudService from '../services/crud.service';
import { ref } from 'vue';

export default {
  data(){
    return{
      newItem: '',
      items: [],
    }
  },

  async mounted(){
    await this.readItems();
  },

  methods: {
    async readItems(){
      const results = await CrudService.readItems();
      this.items = [];//add this line to clear items firstly
      results.data.forEach(element => {
        ref(this.items.push(element));
      });
    },

    async createItem(){
      await CrudService.createItem({ item: this.newItem });
      await this.readItems();//add this line
    }
  }
}
</script>