这里介绍了Vue语法中 v-bind 指令的5种用法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<!-- 一:绑定变量 -->
<div id="app">
<a v-bind:href='bdURL'>百度</a>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
bdURL: 'https://www.baidu.com'
}
})
</script>
<hr>
<!-- 二:绑定方法 -->
<div id="app2">
<a :href="getURL()">百度</a>
</div>
<script>
const app2 = new Vue({
el: '#app2',
methods: {
getURL: function () {
return 'https://www.baidu.com';
}
}
})
</script>
<hr>
<!-- 三:绑定对象 -->
<style>
.active {color: aqua;}
.line {font-weight: bolder;}
</style>
<div id="app3">
<p v-bind:class="{active:isActive, line:isLine}">{{msg}}</p>
<p v-bind:class='getClass()'>{{msg2}}</p>
<button v-on:click='btnFun'>click me</button>
</div>
<script>
const app3 = new Vue({
el: '#app3',
data: {
msg: '直接绑定对象',
msg2:'通过方法返回对象',
isActive: true,
isLine: true
},
methods: {
btnFun: function () {
this.isActive = !this.isActive;
this.isLine = !this.isLine;
},
getClass: function(){
return {active:this.isActive, line:this.isLine};
}
}
})
</script><hr>
<!-- 四:绑定数组 -->
<style>
.color {color: aqua;}
.weight {font-weight: bolder;}
</style>
<p id="app4" v-bind:class="['color','weight']">绑定数组</p>
<script>
const app4 = new Vue({
el:'#app4',
})
</script><hr>
<!-- 五:绑定style -->
<div id="app5">
<!--font-size要加引号,因为对象里不支持连接符-->
<p v-bind:style="{'font-size':size,color:color}">对象形式绑定style</p>
<!--此处25px要加引号,否则会被当作变量-->
<p v-bind:style="{'font-size':'25px'}">123</p>
<p v-bind:style="{'font-size': num +'px'}">456</p>
<!-- 调用方法的方式绑定 -->
<p v-bind:style="getStyle()">789</p>
<p v-bind:style="getStyle2()">000</p>
</div>
<script>
const app5 = new Vue({
el:'#app5',
data:{
num:25,
size: '25px',
color:'green'
},
methods:{
getStyle:function(){
return {'font-size':this.size};
},
getStyle2:function(){
return [{'font-size':this.size},{color:this.color}];
}
}
})
</script>
</body>
</html>
更多相关内容大家可以前往我的个人博客浏览:eyes++的个人空间