vue 实现穿透
在 Vue 中,"穿透"通常指样式穿透(Scoped CSS 的穿透)或事件穿透(Event Bubbling)。以下是两种常见场景的实现方法:
样式穿透(Scoped CSS)
在 Vue 单文件组件中,使用 scoped 属性时,样式默认只作用于当前组件。穿透样式可以使用 ::v-deep 或 /deep/(旧版)。
<style scoped>
/* 新版语法 */
::v-deep .child-class {
color: red;
}
/* 旧版语法(不推荐) */
/deep/ .child-class {
font-size: 16px;
}
</style>
事件穿透(Event Bubbling)
Vue 默认支持原生 DOM 事件冒泡,但自定义事件需要手动处理。
<template>
<div @click="handleParentClick">
<child-component @custom-event="handleChildEvent" />
</div>
</template>
<script>
export default {
methods: {
handleParentClick() {
console.log('Parent clicked');
},
handleChildEvent() {
console.log('Child event received');
}
}
}
</script>
属性穿透(Attribute Inheritance)
非 props 定义的属性会自动继承到子组件的根元素上。可通过 inheritAttrs: false 禁用,并用 v-bind="$attrs" 手动控制。
<template>
<child-component v-bind="$attrs" />
</template>
<script>
export default {
inheritAttrs: false
}
</script>
组件实例穿透(Ref 链)
通过 ref 获取子组件实例实现穿透操作:
<template>
<child-component ref="child" />
</template>
<script>
export default {
mounted() {
this.$refs.child.someMethod();
}
}
</script>
注意:过度使用穿透可能破坏组件封装性,建议优先通过 props/emit 规范通信。







