网站添加ico,购物网站平台建设,商丘网站制作费用,wordpress公众号模板下载一、:class 动态绑定类名
v-bind:class#xff08;缩写为 :class#xff09;可以动态地绑定一个或多个 CSS 类名。
1. 对象语法
通过对象语法#xff0c;可以根据条件动态切换类名。
templatediv :class{ greenText: isActive, red-text: hasError }缩写为 :class可以动态地绑定一个或多个 CSS 类名。
1. 对象语法
通过对象语法可以根据条件动态切换类名。
templatediv :class{ greenText: isActive, red-text: hasError }海绵宝宝不喜欢侬喜欢章鱼哥。/div
/templatescript
export default {data() {return {isActive: true,hasError: false,};},
};
/scriptstyle
.greenText {color: green;
}
.red-text {color: red;
}
/stylegreenText当 isActive 为 true 时添加 greenText 类。red-text当 hasError 为 true 时添加 red-text 类。
效果图
2. 数组语法
通过数组语法可以同时绑定多个类名。
templatediv :class[textClass, bgcClass]海绵宝宝不喜欢侬喜欢章鱼哥。/div
/templatescript
export default {data() {return {textClass: greenText,bgcClass: pinkBgc,};},
};
/scriptstyle
.greenText {color: green;
}
.pinkBgc {width: 300px;height: 200px;background-color: pink;margin: 200px auto;
}
/styletextClass 和 bgcClass 是数据属性它们的值会同时作为类名绑定到元素上。
效果图
3. 结合计算属性
当类名的逻辑较为复杂时可以使用计算属性来动态生成类名对象。
templatediv :classcomputedClass海绵宝宝不喜欢侬喜欢章鱼哥。/div
/templatescript
export default {data() {return {isActive: true,hasError: true};},computed: {computedClass() {return {greenText: this.isActive !this.hasError,text-red: this.hasError};}}
};
/scriptstyle
.greenText {color: green;
}
.text-red{color: red;
}
/stylegreenTextisActive 为true并且hasError为false的时候生效text-redhasError 为true的时候生效 效果图
二、:style 动态绑定内联样式
v-bind:style缩写为 :style可以动态地绑定内联样式。
1. 对象语法
通过对象语法可以直接绑定样式对象。
templatediv :style{ color: activeColor, fontSize: fontSize px }海绵宝宝不喜欢侬喜欢章鱼哥。/div
/templatescript
export default {data() {return {activeColor: red,fontSize: 12};},
};
/scriptactiveColor 和 fontSize 是数据属性它们的值会作为样式绑定到元素上。 效果图
2. 数组语法
通过数组语法可以同时绑定多个样式对象。
templatediv :style[styles1, styles2]海绵宝宝不喜欢侬喜欢章鱼哥。/div
/templatescript
export default {data() {return {styles1: {color: red,fontSize: 14px},styles2: {fontWeight: bold,textDecoration: underline}};},
};
/scriptstyles1 和 styles2 的所有样式都会绑定到元素上。 效果图
3. 使用三元表达式
可以在 :style 中使用三元表达式根据条件动态设置样式值。
templatediv :style{ color: isActive ? green : red }海绵宝宝不喜欢侬喜欢章鱼哥。/div
/templatescript
export default {data() {return {isActive: true};},
};
/script效果图
4. 使用模板字符串
可以使用模板字符串动态拼接样式值。
templatediv :stylecolor: ${isActive ? green : red}; font-size: ${fontSize}px classdemo海绵宝宝不喜欢侬喜欢章鱼哥。/div
/templatescript
export default {data() {return {isActive: false,fontSize: 12};},
};
/script效果图
祝大家新年快乐