v-bind基本使用
作用:动态绑定指令
语法糖::
预期:any(with argument),任意参数 | Object(without argument),对象
参数:attrOrProp(optional)
v-bind:title='doubi'
v-bind是指令
title是参数
doubi是预期值
v-bind用于绑定一个或多个属性值,或者向另一个组件传递props值
在开发中需要动态绑定的属性:图片的src、网站的href、动态绑定一些类、样式等
data: {
link: "https://www.baidu.com",
},
<a v-bind:href="link">百度</a>
动态绑定class(对象语法)
对象语法含义:class后面跟的是一个对象
对象语法用法:
- 直接通过{}绑定一个类
.active {
color: red;
}
<h2 :class="{'active':isActive}" @click='btnClick'>你好</h2>
data: {
isActive: true,
isLine: true
},
methods: {
btnClick: function () {
this.isActive = !this.isActive
}
}
isActive为true,文字显示红色,当点击时,isActive为false,文字显示默认颜色黑色
- 也可以通过判断,传入多个值
<h2 class="title" :class="{'active': isActive, 'line': isLine}">你好</h2>
- 可以和普通的类同时存在
<h2 class="title" :class="{'active': isActive, 'line': isLine}">你好</h2>
- 如果过于复杂,可以放在methods或computed中
methods: {
getClasses: function () {
return {
active: this.isActive,
line: this.isLine
}
}
}
<h2 :class="getClasses()">你好</h2>
动态绑定class(数组语法)
- 可以直接通过[]绑定一个类
[]中是字符串形式,绑定的是名字为active的类
<h2 :class="['active']">Hello World</h2>
.active {
color: aqua;
}
[]中引用的是data中名为active的数据,绑定的类为aaaa
<h2 class="title" :class="[active]">Hello World</h2>
data: {
active: 'aaaa',
},
.aaaa {
color: red;
}
- 可以传入多个值
<h2 :class=“[‘active’, 'line']">Hello World</h2>
<h2 :class="[active, line]">Hello World</h2>
- 和普通的类同时存在,并不冲突
<h2 class="title" :class="['active', 'line']">Hello World</h2>
<h2 class="title" :class="[active, line]">Hello World</h2>
- 如果过于复杂,可以放在一个methods或者computed中
<h2 class="title" :class="getClasses()">Hello World</h2>
methods: {
getClasses: function () {
return [this.active, this.line]
}
}
动态绑定style(对象语法)
<h2 :style="{key(属性名):value(属性值)}">{{message}}</h2>
属性名写法
- 与css写法相同时,需要加’’,否则会报错
- 当使用驼峰命名法时,不需要加’’
50px必须加‘’,否则会被当成 一个变量来解析
<h2 :style="{'font-size' : '50px'}">{{message}}</h2>
<h2 :style="{fontSize : '50px'}">{{message}}</h2>
也可以传入值
data: {
message: "你好啊!",
finalSize1: "100px",
finalSize2: 100,
finalColor: "red",
},
<h2 :style="{fontSize : finalSize1}">{{message}}</h2>
<h2 :style="{fontSize : finalSize2 + 'px'}">{{message}}</h2>
可以传入多个style
<h2 :style="{fontSize : finalSize1 , color : finalColor}">{{message}}</h2>
如果过于复杂,可以放在一个methods或者computed中
methods: {
finalStyle: function () {
return { fontSize: this.finalSize1, color: this.finalColor };
},
},
<h2 :style="finalStyle()">{{message}}</h2>
动态绑定style(数组语法)
可以同时绑定多个style
data : {
message : '你好啊!',
baseStyle1 : {backgroundColor : 'red' , fontSize : '50px'},
baseStyle2 : {color : 'blue'}
}
<h2 :style='[baseStyle1 , baseStyle2]'>{{message}}</h2>