Vue2 子组件 Props 传参动态控制 CSS 类
在 Vue.js 中,可以通过绑定 class 属性来动态改变子组件的 CSS 类。通过 props 属性传递的参数可以在子组件中使用,然后根据参数的值来决定 CSS 类的类型。
在子组件的模板中,可以使用 v-bind 指令将父组件传递的参数绑定到 class 属性上,然后根据参数的值来动态添加或移除 CSS 类。例如:
<template>
<div :class='getClassName'>{{ message }}</div>
</template>
<script>
export default {
props: {
messageType: {
type: String,
required: true
},
message: {
type: String,
required: true
}
},
computed: {
getClassName() {
return {
'success': this.messageType === 'success',
'error': this.messageType === 'error',
'warning': this.messageType === 'warning'
}
}
}
}
</script>
<style scoped>
.success {
color: green;
}
.error {
color: red;
}
.warning {
color: orange;
}
</style>
在上面的例子中,子组件接受两个 props 参数:'messageType' 和 'message'。在子组件的模板中,通过 ':class' 绑定了一个计算属性 'getClassName',根据 'messageType' 的值来动态添加不同的 CSS 类。然后在样式中分别定义了 '.success'、'.error' 和 '.warning' 的 CSS 样式。
这样,当父组件传递不同的 'messageType' 参数给子组件时,子组件会根据参数的值来应用相应的 CSS 类,从而改变显示的样式。
原文地址: https://www.cveoy.top/t/topic/pjYe 著作权归作者所有。请勿转载和采集!