首页 > 解决方案 > Laravel,Vue fetch什么都不返回,但控制台中有数据

问题描述

在我的 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 视图中,它什么都不返回,但在控制台中它有数据..这是显示它的正确方法吗?

标签: laravelvue.js

解决方案


  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)
  })
}

推荐阅读