操作元素的 class 列表和内联样式是数据绑定的一个常见需求。因为它们都是 attribute
,所以我们可以用 v-bind
处理它们:只需要通过表达式计算出字符串结果即可。不过,字符串拼接麻烦且易错。因此,在将 v-bind
用于 class
和 style
时,Vue.js
做了专门的增强。表达式结果的类型除了字符串之外,还可以是对象或数组。
文章目录
绑定 HTML Class
对象语法
我们可以传给 :class
(v-bind:class
的简写) 一个对象,以动态地切换 class:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/vue@next"></script>
<!--导入lodash库-->
<script src="https://unpkg.com/lodash@4.17.20/lodash.min.js"></script>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
</head>
<body>
<div id="app1" >
<div :class="{'active':isActive}"></div>
</div>
</body>
<script>
const vm = Vue.createApp({
data() {
return {
isActive: true,
}
}
}).mount('#app1')
</script>
</html>
实际的页面效果
值得注意的是这种方式不无法在 最大app1 层级生效,假设代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/vue@next"></script>
<!--导入lodash库-->
<script src="https://unpkg.com/lodash@4.17.20/lodash.min.js"></script>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
</head>
<body>
<div id="app1" :class="{'active':isActive}">
<div :class="{'active':isActive}"></div>
</div>
</body>
<script>
const vm = Vue.createApp({
data() {
return {
isActive: true,
}
}
}).mount('#app1')
</script>
</html>
实际结果
上面的语法表示 active
这个 class
存在与否将取决于 data property isActive
的 truthiness。
你可以在对象中传入更多字段来动态切换多个 class。此外,:class
指令也可以与普通的 class
attribute 共存。当有如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/vue@next"></script>
<!--导入lodash库-->
<script src="https://unpkg.com/lodash@4.17.20/lodash.min.js"></script>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
</head>
<body>
<div id="demo" class="static">
<div :class="{ active: isActive, 'text-danger': hasError }">
</div>
</div>
</body>
<script>
const vm = Vue.createApp({
data() {
return {
isActive: true,
hasError: false
}
}
}).mount('#demo')
</script>
</html>
渲染的结果为
<div class="static active"></div>
当 isActive
或者 hasError
变化时,class 列表将相应地更新。例如,如果 hasError
的值为 true
,class 列表将变为 "static active text-danger"
。
绑定的数据对象不必内联定义在模板里:
<div class="static" :class="classObject"></div>
渲染的结果和上面一样。我们也可以在这里绑定一个返回对象的计算属性。这是一个常用且强大的模式:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/vue@next"></script>
<!--导入lodash库-->
<script src="https://unpkg.com/lodash@4.17.20/lodash.min.js"></script>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
</head>
<body>
<div id="demo">
<div class="static" :class="classObject"></div>
</div>
</body>
<script>
const vm = Vue.createApp({
data() {
return {
isActive: true,
hasError: false
}
},
computed: {
classObject() {
return {
active: this.isActive,
'text-danger': this.hasError
}
}
}
}).mount('#demo');
</script>
</html>
数组语法
我们可以把一个数组传给 :class,以应用一个 class 列表:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/vue@next"></script>
<!--导入lodash库-->
<script src="https://unpkg.com/lodash@4.17.20/lodash.min.js"></script>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
</head>
<body>
<div id="demo">
<div class="static" :class="[activeClass, errorClass]"></div>
</div>
</body>
<script>
const vm = Vue.createApp({
data() {
return {
activeClass: 'active',
errorClass: 'text-danger'
}
}
}).mount('#demo');
</script>
</html>
渲染的结果为:
<div class="active text-danger"></div>
这样写将始终添加 errorClass
,但是只有在 isActive
为 truthy 时才添加 activeClass
。
不过,当有多个条件 class
时这样写有些繁琐。所以在数组语法中也可以使用对象语法:
<div :class="[{ active: isActive }, errorClass]"></div>
在组件上使用
这个章节假设你已经对 Vue 组件有一定的了解。当然你也可以先跳过这里,稍后再回过头来看。
当你在带有单个根元素的自定义组件上使用 class attribute
时,这些 class
将被添加到该元素中。此元素上的现有 class
将不会被覆盖。
例如,如果你声明了这个组件:
// Define a new global component called button-counter
app.component('button-counter', {
data() {
return {
count: 0
}
},
template: `
<button class="foo bar" v-on:click="count++">
You clicked me {{ count }} times.
</button>`
})
然后在使用它的时候添加一些 class:
<div id="components-demo">
<button-counter class="baz boo"></button-counter>
</div>
HTML 将被渲染为:
<button class="foo bar baz boo"> You clicked me 0 times. </button>
代码样例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/vue@next"></script>
<!--导入lodash库-->
<script src="https://unpkg.com/lodash@4.17.20/lodash.min.js"></script>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
</head>
<body>
<div id="components-demo">
<button-counter class="baz boo"></button-counter>
</div>
</body>
<script>
// Create a Vue application
const app = Vue.createApp({
})
// Define a new global component called button-counter
app.component('button-counter', {
data() {
return {
count: 0
}
},
template: `
<button class="foo bar" v-on:click="count++">
You clicked me {{ count }} times.
</button>`
})
app.mount('#components-demo')
</script>
</html>
对于带数据绑定 class 也同样适用:
<button-counter class="baz boo"></button-counter>
当 isActive 为 truthy 时,HTML 将被渲染成为:
<button class="foo bar active baz boo"> You clicked me 0 times. </button>
如果你的组件有多个根元素,你需要定义哪些部分将接收这个 class。可以使用 $attrs
组件 property
执行此操作:
<div id="app">
<my-component class="baz"></my-component>
</div>
const app = Vue.createApp({})
app.component('my-component', {
template: `
<p :class="$attrs.class">Hi!</p>
<span>This is a child component</span>
`
})
你可以在非 Prop 的 Attribute小节了解更多关于组件属性继承的信息。
绑定内联样式
对象语法
:style
的对象语法十分直观——看着非常像 CSS,但其实是一个 JavaScript 对象。CSS property 名可以用驼峰式 (camelCase) 或短横线分隔 (kebab-case,记得用引号括起来) 来命名:
<div id="demo">
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }">
<p>123</p>
</div>
</div>
data() {
return {
activeColor: 'red',
fontSize: 30
}
}
HTML 将被渲染成为:
<div style="color: red; font-size: 30px;"><p> 123 </p></div>
代码样例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/vue@next"></script>
<!--导入lodash库-->
<script src="https://unpkg.com/lodash@4.17.20/lodash.min.js"></script>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
</head>
<body>
<div id="demo">
<div :style="{ color: activeColor, fontSize: fontSize + 'px' }">
<p>123</p>
</div>
</div>
</body>
<script>
const vm = Vue.createApp({
data() {
return {
activeColor: 'red',
fontSize: 30
}
}
}).mount('#demo');
</script>
</html>
直接绑定到一个样式对象通常更好,这会让模板更清晰:
<div :style="styleObject"></div>
data() {
return {
styleObject: {
color: 'red',
fontSize: '13px'
}
}
}
同样的,对象语法常常结合返回对象的计算属性使用。
数组语法
:style
的数组语法可以将多个样式对象应用到同一个元素上:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/vue@next"></script>
<!--导入lodash库-->
<script src="https://unpkg.com/lodash@4.17.20/lodash.min.js"></script>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<style>
.basic{
width: 400px;
height: 100px;
border: 1px solid black;
}
.happy{
border: 4px solid red;;
background-color: rgba(255, 255, 0, 0.644);
background: linear-gradient(30deg,yellow,pink,orange,yellow);
}
.sad{
border: 4px dashed rgb(2, 197, 2);
background-color: gray;
}
.normal{
background-color: skyblue;
}
.atguigu1{
background-color: yellowgreen;
}
.atguigu2{
font-size: 30px;
text-shadow:2px 2px 10px red;
}
.atguigu3{
border-radius: 20px;
}
</style>
</head>
<body>
<div id="demo">
<!-- 绑定class样式--数组写法,适用于:要绑定的样式个数不确定、名字也不确定 -->
<div class="basic" :class="classArrayValue" @click="changeMoodClassArr">{{name}}</div> <br/><br/>
</div>
</div>
</body>
<script>
const vm = Vue.createApp({
data() {
return {
name:'死神只在金州降临',
classArrayValue:'normal',
classArr: ['happy','sad','normal']
}
},
methods: {
changeMood(){
this.mood = 'happy';
},
changeMoodClassArr(){
const index = Math.floor(Math.random()*3);
this.classArrayValue = this.classArr[index];
}
},
}).mount('#demo');
</script>
</html>
自动添加前缀
在 :style
中使用需要一个 vendor prefix (浏览器引擎前缀) 的 CSS property 时,Vue 将自动侦测并添加相应的前缀。Vue 是通过运行时检测来确定哪些样式的 property 是被当前浏览器支持的。如果浏览器不支持某个 property,Vue 会进行多次测试以找到支持它的前缀。
多重值
可以为 style 绑定中的 property 提供一个包含多个值的数组,常用于提供多个带前缀的值,例如:
<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div>
这样写只会渲染数组中最后一个被浏览器支持的值。在本例中,如果浏览器支持不带浏览器前缀的 flexbox,那么就只会渲染 display: flex。