【问题标题】:Loading component after fetch in vuejs在 vuejs 中获取后加载组件
【发布时间】:2020-06-20 08:19:41
【问题描述】:

我正在尝试使用 axios 使用 API。

这是我到目前为止的代码

<select>
    <option v-for="value in values"> value.name </option>
</select>

   // js
   data(){
        values: [],
   },
   created() {
        this.getData();
   },

   methods: {
       getData: () => {
          axios.get('url')
          .then(res => {
              this.value = res.data.dados;
              console.log(res.data.dados);
          })
          .catch(error => {
               console.log(error);
          });
   }
}

promise 的 console.log 工作正常,但未呈现带有数据的选项。 这可能是因为我的选择组件是在“getData()”之前呈现的。我该如何解决?

【问题讨论】:

    标签: api vue.js components fetch


    【解决方案1】:

    只需放置一个加载处理程序。

    <select v-if="loaded">
      <option v-for="value in values"> value.name </option>
    </select>
    
       // js
       data(){
            values: [],
            loaded: false,
       },
       created() {
            this.getData();
       },
    
       methods: {
           getData: () => {
              axios.get('url')
              .then(res => {
                  this.value = res.data.dados;
                  this.loaded = true;
              })
              .catch(error => {
                   console.log(error);
                   this.loaded = true;
              });
       }
    }
    

    【讨论】:

      【解决方案2】:

      你在this.value 上有错字,应该是this.values。如果这不起作用,请使用this.$forceUpdate() 强制重新渲染组件

      <select>
          <option v-for="value in values">{{ value.name }}</option>
      </select>
      
         // js
         data(){
              values: [],
         },
         created() {
              this.getData();
         },
      
         methods: {
             getData: () => {
                axios.get('url')
                .then(res => {
                    this.values = res.data.dados; // change value to values
                    console.log(res.data.dados);
                    this.$forceUpdate(); // add forceUpdate
                })
                .catch(error => {
                     console.log(error);
                });
         }
      }
      

      【讨论】:

      • 不是错字。现在,它说“TypeError: _this.$forceUpdate is not a function at eval (Pesquisa.vue?cddd:49)”
      • 您尝试将this.value 更改为this.values 吗?
      • 哦 forceUpdate 错误,因为创建时调用的函数,您可以将其更改为挂载
      猜你喜欢
      • 2017-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 2018-03-25
      • 1970-01-01
      • 2021-12-29
      • 2022-10-21
      相关资源
      最近更新 更多