事件、属性透传:父自定义的属性、事件都可以透传给子与孙
父App.vue
<template>
<div>
<!-- 属性透传 -->
<Navbar class="navbar" id="navbar" style="background-color: red;" @click="handleClick()"></Navbar>
</div>
</template>
<script>
import Navbar from './Navbar.vue'
export default {
data() {
return {
}
},
methods: {
handleClick() {
console.log('App父组件定义的事件');
}
},
components: {
Navbar,
}
}
</script>
<style lang="scss" scoped></style>
子组件Navbar.vue
<template>
//分别对应下面的截图
<div>
子
<button>test</button>
</div>
<!-- <NavbarChild></NavbarChild> -->
</template>
<script>
import NavbarChild from './NavbarChild.vue'
export default {
components: {
NavbarChild
}
}
</script>
<style lang="scss" scoped></style>
孙NavbarChild.vue
<template>
<div>
孙
</div>
</template>
<script>
</script>
<style lang="scss" scoped></style>
运行截图:
要是不想属性或事件透传到子组件的根节点上,则可以加下面的属性
父组件依旧如上图所示:不变
子组件加了inheritAttrs:false
<template>
<div>
子
<!-- 接收父组件传过来自定义属性 -->
<button v-bind="$attrs">test</button>
</div>
</template>
<script>
import NavbarChild from './NavbarChild.vue'
export default {
// 禁止透传到根节点上 ,如果想指定透传的位置但不想透传到跟根节点上,可以使用v-bind,最终会透传的指定位置上
inheritAttrs: false,
components: {
NavbarChild
}
}
</script>
<style lang="scss" scoped></style>
运行截图:
点击按钮test控制台才会输出:
注意看:这一次子组件绑定的位置跟上面的不一样,这个绑定在button上,而不是直接绑定到根节点上
未完待续...下一节复习一个属性透传案例