【问题标题】:Parent component updates a child component v-for list, the new list is not rendered in the viewport (vue.js)父组件更新子组件 v-for 列表,新列表不在视口中渲染(vue.js)
【发布时间】:2021-06-05 09:50:49
【问题描述】:

我的应用结构如下。父应用程序有一个可编辑的表单,旁边有一个子组件列表。子组件是表格中的学生列表。

我正在尝试更新子组件列表。子组件使用'v-for',列表是通过使用 Axios 的 Web 服务调用生成的。

在我的父组件中,我正在编辑学生姓名,但学生姓名未反映在我在屏幕上的列表中。

例子:

注意左侧的父表单已更新的名称现在存储在数据库中。但是,列表(子组件)保持不变。

我尝试了一些方法,例如使用 props、ref 等。我开始认为我的应用架构可能不正确。

有谁知道我该如何解决这个问题。

下面的代码部分。你可能明白我是 Vue 的新手。

非常感谢您的帮助。

// Child component
<component>
..
   <tr v-for="student in Students.slice().reverse()" :key="student._id">
..
</component>

export default {
    env: '',
    // list: this.Students,
    props: {
        inputData: Boolean,
    },
    data() {
        return {
            Students: [],
        };
    },
    created() {
    
    // AXIOS web call...
    
    },
};


// Parent component
import List from "./components/students/listTerms";

export default {
  name: "App",
  components: {
    Header,
    Footer,
    List,
  },
};

// Implementation
 <List />

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案1】:

    我认为在这种情况下最好使用vuex 并使用mutations 进行更改。因为当您更改数据数组中的对象时,它不会被覆盖。反应性不起作用 阅读更多关于它的信息here

    【讨论】:

      【解决方案2】:

      如果您的列表组件在每次提交表单时都没有进行新的 API 调用,则数据不会反映所做的更改。但是,当组件是表单组件的子组件时,每次发出单独的请求没有多大意义。

      为了利用 Vue 的反应性并防止开销,最好使用 props。

      作为一个简化的例子:

      // Child component
      <template>
      ...
        <tr v-for="student in [...students].reverse()" :key="student._id">
      ...
      </template>
      
      <script>
      export default {
        props: {
          students: Array,
        },
      };
      </script>
      
      // Parent component
      <template>
        <div>
          <form @submit.prevent="submitForm">
            <input v-model="studentData.name" />
            <input type="submit" value="SUBMIT" />
          </form>
          <List :students="students" />
        </div>
      </template>
      
      <script>
      import List from "./components/students/listTerms";
      
      export default {
        name: "App",
        components: {
          List,
        },
        data() {
          return {
            students: [],
            studentData: {
              name: ''
            }
          }
        },
        methods: {
          submitForm() {
            this.$axios.post('/endpoint', this.studentData).then(() => {
              this.students.push({ ...this.studentData });
            }).catch(err => {
              console.error(err)
            })
          }
        }
      };
      </script>
      

      Working example.

      这样可以确保未成功存储的数据不会被显示,并且存储成功的数据会反映在子组件中。

      【讨论】:

      • 谢谢,这就是答案。我的架构不正确。父母应该向孩子调用事件并引起反应。这没有发生。
      猜你喜欢
      • 2021-07-11
      • 1970-01-01
      • 2018-04-16
      • 2018-02-08
      • 2017-03-05
      • 2018-08-12
      • 2019-01-31
      • 1970-01-01
      • 2019-06-01
      相关资源
      最近更新 更多