【发布时间】:2022-01-15 17:50:46
【问题描述】:
我需要帮助。我是 Vue3 的业余爱好者,不明白为什么会发生这种情况:
如果我在父组件中设置:
props: [ 'code' ],
data() {
return {
asset: {
id: '',
brand: '',
group: {
name: '',
area: ''
}
}
}
},
created() {
axios.get('/api/myUrl/' + this.code, {})
.then(response => {
if (response.status === 200) {
this.asset = response.data;
}
})
.catch(error => {
console.log(error);
})
}
然后,在我的组件<asset-insurance :asset_id="asset.id"></asset-insurance> 中,asset_id 属性为空。
但是,如果我设置:
props: [ 'code' ],
data() {
return {
asset: []
}
},
created() {
axios.get('/api/myUrl/' + this.code, {})
.then(response => {
if (response.status === 200) {
this.asset = response.data;
}
})
.catch(error => {
console.log(error);
})
}
然后,asset_id prop 在 <asset-insurance> 组件中获得了正确的 asset.id 值,但我在有关资产的主要组件中收到了一些警告和错误属性 group.name 未设置(但它在模板中正确呈现)。
可能我做错了什么,但我找不到问题出在哪里。有什么帮助吗?
编辑:
我只是通过 console.logging 来检查子组件 AssetInsurance 中的 prop
<script>
export default {
name: "AssetInsurance",
props: [
'asset_id'
],
created() {
console.log(this.asset_id)
}
}
</script>
asset_id 只是一个整数,并且在父数据asset.id 中被正确分配,因为我也在父模板中渲染它。
【问题讨论】:
-
您发布的代码没有解释问题。如果数据是您所期望的,它应该可以工作。不知道您如何确定道具不正确。最简单的方法是只输出asset.id 值,不需要子组件。请提供stackoverflow.com/help/mcve 进行复制。 Stackblitz 等的工作演示可能有助于更快地获得答案。但是将asset定义为数组然后赋值对象是错误的。
-
@EstusFlask,谢谢,但很抱歉我不知道如何使用 Stackblitz。我已经编辑了我的问题,以澄清在 api 调用中正确分配了asset.id,并且子组件中的直接console.log 显示当我用属性定义资产时没有传递prop,但是当它传递正确时将资产声明为数组。 :(
-
我发布了解释。您不会在 created 钩子中获得道具值,因为它不存在。我猜你只是在使用
asset数组时破坏了组件(这是错误的原因),所以当asset.id 可用时第二次重新安装子组件,而在正常情况下不应该。当登录对象时也要注意这一点(这里不是这种情况)stackoverflow.com/questions/23392111/console-log-async-or-sync