【问题标题】:Laravel, Vue fetch returns nothing but there is data in consoleLaravel,Vue fetch什么都不返回,但控制台中有数据
【发布时间】:2019-01-03 05:30:56
【问题描述】:

在我的 vue 模板中,我有这个...

<template>
   <div id="container">
      {{show_municipality_in_words(12)}}
   </div>
</template>

在我的 js 中...

export default {
   data() {
   },
   methods: {
     show_municipality_in_words(municipality_id) {
      fetch(`api/biodidb/get_municipality_name_by_id/${municipality_id}`)
       .then(response => response.json())
       .then(result => {
         console.log(result.Municipality);
         return result.Municipality;
       }).catch(err => {console.log(err)});
     }
   }
}

在 html 视图中,它什么都不返回,但在控制台中它有数据.. 这是显示它的正确方式吗?

【问题讨论】:

    标签: laravel vue.js


    【解决方案1】:
    1. 您的方法没有返回任何内容,因此没有要渲染的内容。
    2. 您的方法是异步的,因此即使您愿意也无法返回任何值。

    TL;DR尽量避免在模板中使用方法,而是将数据加载到data 属性中。例如

    <template>
      <div id="container">
        <span v-if="municipality">{{ municipality }}</span>
        <span v-else>Loading...</span> <!-- ? totally optional -->
      </div>
    </template>
    
    data () {
      return { municipality: null }
    },
    methods: {
      loadMunicipality (id) {
        return fetch(`api/biodidb/get_municipality_name_by_id/${id}`)
            .then(res => res.json())
            .then(obj => obj.Municipality)
      }
    },
    created () {
      this.loadMunicipality(12).then(municipality => {
        this.municipality = municipality
      }).catch(err => {
        console.error(err)
      })
    }
    

    【讨论】:

    猜你喜欢
    • 2020-03-11
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多