【发布时间】:2019-06-07 13:43:16
【问题描述】:
您好,我正在尝试将一个值作为道具传递给子组件,并尝试在子组件的 created 钩子中使用该值,但它没有被设置。请参阅下面的示例,
<!-- Parent component -->
<template>
<div>
<details
:customer_id = this.customer_id
:foo = "bar" />
</div>
</template>
<script>
import CustomerDetail from './CustomerDetails';
export default {
name: 'Customer',
data: function() {
return {
customer_id: '',
}
components: {
'detail': CustomerDetail
},
created: function() {
var id = this.$route.params.id;
this.customer_id = id;
} // created
}
</script>
<!-- Details component -->
<template>
<div>
<h1>{{foo}}</h1>
</div>
</template>
<script>
export default {
name: 'CustomerDetail',
props: ['customer_id', 'foo']
created: function() {
console.log(this.customer_id); <!-- -->
} // created
}
</script>
如上代码所示,在渲染子组件时,可能会多次未定义子组件的created()钩子中的customer_id。如果热加载发生在同一个视图上,它偶尔会出现。如何确保此值始终可用。在这种情况下,我想做服务器调用以获取客户详细信息。同时 {{foo}} 正确显示值 'bar'。我错过了什么?任何帮助表示赞赏。
【问题讨论】:
-
这一行的
undefined也必须是var id = this.$route.params.id;。如果id确实存在,请先尝试控制台记录它。 -
它不是未定义的,因为父组件是从路由器调用中呈现的。我遵循路由代码,{ path: '/customers/:id', component: Customer }
-
您不需要模板中的
this.customer_id中的this。也请发布您的路由器对象。 -
我得到 linter 错误,而在子组件中没有使用 'this'。错误字符串是“模块警告(来自./node_modules/eslint-loader/index.js):错误:'customer_id'未定义(no-undef)”
-
您能否创建一个小提琴或代码框,我们可以在其中看到发生的问题。我在本地尝试过,无法重现。
标签: vue.js vue-component