v-bind指令用于给html标签设置属性。
<!-- 完整语法 --> <a v-bind:href="url"></a> <!-- 缩写 --> <a :href="url"></a>
v-bind入门
<div id="app">
<div v-bind:id="id1">文字</div>
</div>
<script>
new Vue({
el: '#app',
data: {
id1: 'myid'
}
})
</script>
会渲染如下:
<div id="myid">文字</div>
字符串拼接
<span :text=' "we" + 1 '>使用</span>
会渲染如下:
<span text='we1'>使用</span>
运算:
<div :text='1 + 2'>test</div>
会渲染如下:
<div text="3">test</div>
调用函数:
<div :text='getText()'>test</div>
......
<script>
export default {
methods: {
getText() {
return "this is text"
}
}
}
</script>
渲染成:
<div text="this is text">test</div>
使用对象:
<template>
<div class="hello">
<div :text='obj'>test</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
obj: Object()
}
}
}
</script>
结果:
<div text="[object Object]">test</div>
如果对象有toString方法:
<template>
<div class="hello">
<div :text='obj'>test</div>
</div>
</template>
<script>
var obj = Object()
obj.toString = function(){
return "data in obj"
}
export default {
name: 'HelloWorld',
data () {
return {
obj: obj
}
}
}
</script>
则渲染的是toString方法的值:
<div text="data in obj">test</div>
和数组使用:
<template>
<div class="hello">
<div :text='array'>test</div>
</div>
</template>
<script>
var array = Array()
array[0] = "1"
array[1] = "2"
export default {
name: 'HelloWorld',
data () {
return {
array: array
}
}
}
</script>
渲染为:
<div text="1,2">test</div>
v-bind vs 计算属性
<template>
<div class="hello">
<div :text='myText'>test</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
value: "data"
}
},
computed: {
myText: function(){
return "value is " + this.value
}
}
}
</script>
稍微对比一下,我们不难发现,计算属性和上面的各种功能是一样的,但是在字符串拼接的情况下,使用计算属性的好处是分离了,不在html中写逻辑。所以计算属性是更推荐的用法。
class 属性绑定
<div id="app">
<div v-bind:class="{active: isActive}">文字</div>
</div>
<script>
new Vue({
el: '#app',
data: {
isActive: true
}
})
</script>
如果同时多个类都要判断,则可写成<div v-bind:class="{active: isActive, highlight: isHighlight}">文字</div>。
绑定computed属性:
而且还可以绑定computed里的属性,毕竟data的数据是静态的,computed的属性可以计算:
<div id="app">
<div v-bind:class="classObject">文字</div>
</div>
<script>
new Vue({
el: '#app',
computed: {
classObject: function () {
// 计算过程省略,假设得出了isActive和isDanger的布尔值
return {
'active': isActive,
'text-danger': isDanger
}
}
}
})
</script>
本文深入讲解了Vue.js中v-bind指令的使用方法,包括基本应用、字符串拼接、运算、函数调用、对象和数组使用,以及v-bind与计算属性的区别。此外,还详细介绍了class属性绑定的高级用法。

378

被折叠的 条评论
为什么被折叠?



