【问题标题】:array in vue template is not updatingVue模板中的数组未更新
【发布时间】:2019-07-29 05:53:07
【问题描述】:

我正在我的 vue.xml 中创建一个动态数组。此数组正在从 JSON 数组的脚本中填充,但未在模板中更新。在模板中它返回空白数组。这是我的代码:

<template>
  <div>
    {{users}} <!-- this is returning blank --> 
  </div>
</template>

<script>
  export default {
    data(){
      return {
        users: []
      }
    },
    created(){
      this.fetchUsers();
    },
    methods:{
      fetchUsers(){
        fetch('api/single')
          .then(res => res.json())
          .then(res => {
            this.users= res.data;
              console.log(this.users); //this is showing the data 
      })
        .catch(err => console.log(err));
   }
 }
};
</script>

【问题讨论】:

    标签: javascript arrays vue.js


    【解决方案1】:

    Fetch API 发送异步请求,因此在从 API 加载数据之前显示用户。调用绑定到用户的计算方法。

    【讨论】:

      【解决方案2】:

      当数据属性值没有以正确的方式初始化时会发生这种情况。您应该使用 Vue api 提供的 vm.$set 方法,而不是将 fetch 请求中的数组分配给您的数据属性。由于这种反应性将被保留。事实上,您甚至可以从数据对象中删除用户数组声明,因为 vm.$set 将覆盖它。

      所以你的方法看起来像这样:

      fetchUsers(){
              fetch('api/single')
              .then(res => res.json())
              .then(res => {
                  this.$set(this, 'users', res.data) // target, key, value
              })
              .catch(err => console.log(err));
          }
      

      【讨论】:

        【解决方案3】:

        我认为问题与数组的反应性有关。尝试使用 foreach 循环填充您的数据或按照建议使用 vm.$set

        res.data.forEach(element => {
          this.users.push(element);
        });
        

        有关数组反应性的更多信息,请查看vuejs common gotchas

        【讨论】:

          【解决方案4】:
          this.$nextTick( () => {
            this.fetchUsers();
          })
          

          你可以试试this.$nextTick()。因为 Vue 中 DOM 的更新是异步的。

          【讨论】:

          • fetchUsers() 方法实际上工作正常。问题是 fatch() 中填充的任何内容都没有在 fetch() 之外更新。甚至不在 fetchUsers() 方法中
          猜你喜欢
          • 2020-10-08
          • 1970-01-01
          • 2021-06-20
          • 2017-12-03
          • 1970-01-01
          • 2017-11-23
          • 2020-12-22
          • 2017-05-03
          • 2021-08-09
          相关资源
          最近更新 更多