[英]How to avoid checking object in object to exists in data Vue.js?
<template>
<img :src="user.avatar_thumbnail">
<a :href="user.profile.link"/>
</template>
<script>
export default {
data: function () {
user: {}
},
mounted: function() {
let vm = this;
axios.get('user/profile/<id>').then((response) => {
vm.user = response.data.user
});
}
}
</script>
如果服務器未在對象用戶中發送字段“avatar_thumbnail”,則不會呈現頁面,
所以我可以使用 if else 表達式(三元)但我不能在任何地方都這樣做
<img :src="user.avatar_thumbnail ? user.avatar_thumbnail : '' ">
也許 vuejs 有一些針對這種情況的工具?
和更多服務器發送這樣的對象(嵌套):user.profile.avatar_thumbnail,我不想制作嵌套的三元表達式(請不要推薦我使用計算方法 - 如果我找不到另一個,我會使用它解決方案)
<img :src="user.avatar_thumbnail || '' ">
或者:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
並且,正確
export default {
data: function () {
return {
user: {}
}
},
有許多不同的方法可以解決您的問題。 但是在您給定的代碼中有很多錯誤。 你可以試試這個解決方案
<template>
<div>
<img :src="getThumbnail()" />
<a :href="user.profile.link" />
</div>
</template>
<script>
export default {
data: function() {
return{
user: {}
}
},
methods: {
getThumbnail() {
if (this.user.avatar_thumbnail) {
return this.user.avatar_thumbnail
} else {
return 'default_thumbnil'
}
}
},
mounted: function() {
let vm = this
axios.get('user/profile/<id>').then(response => {
vm.user = response.data.user
})
}
}
</script>
結果很簡單,只需為與您將要接收的對象具有相同結構的對象設置一個默認值。 例如:
data: function () {
user: {
avatar_thumbnail: '',
profile: {
link: ''
}
}
}
您還可以定義一個返回initial
數據的函數,如下所示:
const initialUser = () => {
return {
avatar_thumbnail: '',
profile: {
link: ''
}
}
}
然后在數據屬性中使用它:
data: function () {
user: initialUser()
}
注意:您可能只需要指定模板中使用的對象的屬性來克服潛在的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.