有一個組件A,包含了組件B,組件B包含了組件C,那么組件A就是父組件,組件B就是子組件,組件C就是孫組件。
$attrs可以把父組件的值傳給孫組件
1.在引用的子組件里綁定要傳的值
<template> <div id="app"> <HelloWorld :test="hello"/> </div> </template>
2.在引用的孫組件里用v-bind綁定$attrs
<child v-bind="$attrs"></child>
3.在孫組件里打印出this.$attrs,可以獲取到父組件的數據
mounted(){ console.log(this.$attrs.test); this.cdata = this.$attrs.test }
完整例子:
App.vue 父組件
<template> <div id="app"> <HelloWorld :test="hello"/> </div> </template> <script> import HelloWorld from './components/HelloWorld' export default { name: 'App', components: { HelloWorld }, data(){ return { hello:"hello" } }, } </script>
HelloWorld.vue子組件
<template> <div> <child v-bind="$attrs"></child> </div> </template> <script> import Child from '../components/Child' export default { name: "HelloWorld", components:{ Child }, data () { return { }; } } </script>
Child.vue 孫組件
<template> <div> {{cdata}} </div> </template> <script> export default { name: "Child", data () { return { cdata:"孫組件" }; }, mounted(){ console.log(this.$attrs.test); this.cdata = this.$attrs.test } } </script>