Vue3 样式绑定学习笔记

在 Vue3 中,我们可以通过 v-bind 指令绑定样式。v-bind 的缩写是 ":"。

绑定一个样式

我们可以使用 v-bind:class 绑定一个 CSS 类。可以根据条件动态地切换 class。

Copy Code
<template> <div v-bind:class="{ active: isActive }"></div> </template> <script> export default { data() { return { isActive: true } } } </script> <style> .active { font-weight: bold; color: red; } </style>

绑定多个样式

我们也可以绑定多个样式,只需要传递一个包含多个属性的对象即可。

Copy Code
<template> <div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div> </template> <script> export default { data() { return { activeColor: 'red', fontSize: 30 } } } </script>

使用数组语法

我们还可以将两个绑定的对象合并成一个对象,可以使用数组语法。

Copy Code
<template> <div v-bind:class="[activeClass, errorClass]"></div> </template> <script> export default { data() { return { activeClass: 'active', errorClass: 'text-danger' } } } </script> <style> .active { font-weight: bold; color: red; } .text-danger { color: red; } </style>

条件判断

我们可以通过条件判断来决定是否添加某个样式,例如:

Copy Code
<template> <div v-bind:class="{ 'active': isActive }"></div> </template> <script> export default { data(){ return { isActive: true } } } </script> <style> .active { font-weight: bold; color: red; } </style>

我们还可以使用三元表达式来简化条件判断:

Copy Code
<template> <div v-bind:class="{ 'active': isActive }"></div> </template> <script> export default { data(){ return { isActive: true } } } </script> <style> .active { font-weight: bold; color: red; } </style>

实例

下面是一个使用了样式绑定的实例:

Copy Code
<template> <div v-bind:class="{ 'active': isActive }" v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"> <p>这是一段文字。</p> <button v-on:click="toggleClass">Toggle Class</button> </div> </template> <script> export default { data() { return { isActive: true, activeColor: 'red', fontSize: 30 } }, methods: { toggleClass() { this.isActive = !this.isActive; } } } </script> <style> .active { font-weight: bold; color: red; } </style>

在上面的实例中,我们定义了一个 div 元素,并使用 v-bind:class 和 v-bind:style 绑定了样式。当 isActive 为 true 时,会添加 active 类,并将文本颜色设置为 red,字体大小设置为 30px。当点击 Toggle Class 按钮时,会切换 isActive 的值,从而改变样式。