在我的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视图中,它什么也不返回,但是在控制台中它有数据..这是显示它的正确方法吗?
答案 0 :(得分:0)
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)
})
}