前言
好无奈,每次接口给我的数据都是用一个数组包着,当我想要的数据只是一个对象而不是n个对象时,它也要在外面给我包一个数组,生怕我的“对象”冻死了吧。
我的思路
第一次遇到这样的情况时,我是直接用 array[0] 来获取数组的第一个元素,也就是我想要的那个“对象”。代码如下:
<template>
<div class="info">
大家好,我叫{{ info[0].name }}, 我今年{{ info[0].age }}岁了
</div>
</template>
<script>
export default {
data() {
return {
info: []
}
},
mounted() {
// 模拟接口获取的数据
this.info = [
{
name: "林小饼",
age: 18
}
]
}
};
</script>
<style scoped>
.info {
font-size: 28px;
font-weight: bold;
color: #f5f9ff;
text-shadow: 0 0 5px #ff1200, 0 0 10px #ff1200;
}
</style>
非常不好意思,效果虽出来了,但控制台报错了。彼时年少,疑惑不解,遂问导师,曰(yue):计算属性。。。。。。
正确思路
<template>
<div class="info">
大家好,我叫{{ myInfo.name }}, 我今年{{ myInfo.age }}岁了
</div>
</template>
<script>
export default {
data() {
return {
info: []
}
},
mounted() {
// 模拟接口获取的数据
this.info = [
{
name: "林小饼",
age: 18
}
]
},
computed: {
// 采用计算属性
myInfo(){
const [ myInfo = {} ] = this.info
return myInfo
}
}
};
</script>
<style scoped>
.info {
font-size: 28px;
font-weight: bold;
color: #f5f9ff;
text-shadow: 0 0 5px #ff1200, 0 0 10px #ff1200;
}
</style>