laravel - 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 视图中,它什么都不返回,但在控制台中它有数据..这是显示它的正确方法吗?
解决方案
- 你的方法没有返回任何东西,所以没有什么可以渲染的。
- 您的方法是异步的,因此即使您愿意也无法返回任何值。
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)
})
}
推荐阅读
- linkedin - 使用 LinkedIn 登录:连接问题 (?)
- angularjs - 将列表项名称绑定到图像
- asp.net-web-api - Swagger 使用 Web API 版本控制约束
- scala - org.apache.spark.sql.catalyst.parser.ParseException:在 spark scala cassandra api 中
- javascript - 在javascript中读取文本文件后的返回值
- c# - 如何使用 TFS REST API 作为指定用户更改工作项
- java - JDBC 在视图 v$session 中识别 api 名称
- javascript - Google reCaptcha 响应“未捕获(承诺)为空”
- asynchronous - 不幸的是,xamarin 应用程序已停止选择菜单项
- angular - 带有 [(ngModel)] 的硬编码字符串