实现思路
- 父组件:在父组件中使用作用域插槽,通过向插槽传递数据来控制子组件的样式类名。这样父组件可以根据自身的逻辑决定子组件应用何种样式。
- 子组件:在子组件模板中定义插槽,并接收父组件传递过来的数据,使用这些数据来动态绑定样式类名,从而实现样式根据父组件传入的数据动态调整,避免样式冲突。
代码示例
父组件(App.vue)
<template>
<div id="app">
<ChildComponent>
<template v-slot:default="slotProps">
<div :class="slotProps.customClass">
<!-- 这里放置子组件插槽内容 -->
{{ slotProps.text }}
</div>
</template>
</ChildComponent>
</div>
</template>
<script>
import ChildComponent from './components/ChildComponent.vue';
export default {
name: 'App',
components: {
ChildComponent
}
};
</script>
<style>
/* 父组件自定义样式 */
.parent - style {
color: red;
}
</style>
子组件(ChildComponent.vue)
<template>
<div>
<slot :customClass="getCustomClass" :text="defaultText"></slot>
</div>
</template>
<script>
export default {
data() {
return {
defaultText: '子组件默认文本'
};
},
methods: {
getCustomClass() {
// 这里可以根据子组件的逻辑返回不同的类名
return 'parent - style';
}
}
};
</script>
<style>
/* 子组件自身样式 */
.child - style {
color: blue;
}
</style>