【发布时间】:2023-02-06 19:54:51
【问题描述】:
我想接收父组件绑定到子组件的任何道具,而不在props:[] 中提及,因为我不知道哪些道具会绑定。
父组件
<template>
<div id="parentComponent">
<child-component v-bind="anyPropsToPass"></child-component>
</div>
</template>
<script>
import ChildComponent from './components/child-component/child-component'
export default {
name: 'app',
components: {
ChildComponent
},
data () {
return {
anyPropsToPass: {
name: 'John',
last_name: 'Doe',
age: '29',
}
}
}
}
</script>
子组件
<template>
<div>
<p>I am {{name}} {{last_name}} and i am {{age}} old</p>
<another-child v-bind="$props"></another-child> <!-- another child here and we pass all props -->
</div>
</template>
<script>
import AnotherChild from "../another-child/another-child";
export default {
components: {AnotherChild},
props: [], // I know if I mentioned props here I can receive but it's unknown, I
//just want to pass it down until it received in right component to use
created() {
console.log("Props", this.$props);
// Gets null
// Expected : anyPropsToPass Object
}
}
</script>
如果在 child 的 props 中提到了 props 那么它就可以工作,但是即使我们对 child 不感兴趣,也应该有一些方法可以知道哪些是从父级传递或绑定的 props。
例如工作正常!
子组件
<template>
<div>
<p>I am {{name}} {{last_name}} and i am {{age}} old</p>
<another-child v-bind="$props"></another-child>
</div>
</template>
<script>
import AnotherChild from "../another-child/another-child";
export default {
components: {AnotherChild},
props: ['name', 'last_name'],
created() {
console.log("Props", this.$props);
// Gets expected props here
}
}
</script>
【问题讨论】:
标签: javascript vue.js vuejs2 vue-component