1-4 基本用法-属性
目录:
- 属性绑定和属性简写
- 绑定class属性
- 绑定style属性
一、属性绑定和属性简写
属性绑定:v-bind指令
#全写: v-bind:属性="变量" => 如:v-bind:src="url" #简写 :属性="变量" => :src="url"
用法如下:
<body>
<div id="box">
<!--全写v-bind属性绑定,绑定数据必须vue实例是data中的属性-->
<img v-bind:src="url">
<!--简写写v-bind属性绑定,绑定数据必须vue实例是data中的属性-->
<img :src="url" :width="w" :height="h">
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script>
new Vue({
el: "#box",
data:{
url:"https://www.baidu.com/badidu.png",
w:'200px',
h:'100px',
}
});
</script>
</body>
二、绑定class属性
2.1、class绑定
方式1和方式2(变量和数组的方式):class绑定属性,我们先看看前两种方式吧,其实前两种方式是 通过变量的方式绑定属性,分别通过 单个和多个样式(采用数组方式)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>class属性绑定</title>
<!--定义样式 aa 和 cc-->
<style>
.aa{
color: red;
font-size: 20px;
}
.cc{
background-color: #ccc;
}
</style>
</head>
<body>
<div id="box">
<!--可以访问,普通css的方式-->
<!--<p class="aa">帅高高真帅</p>-->
<!--不可以,Vue的属性绑定是不能直接css样式,绑定的aa是一个变量,在data中并没有找到-->
<!--<p :class="aa">帅高高真帅</p>-->
<!--方式1:变量的形式,bb:是vue实例中data中的变量-->
<p :class="bb">帅高高真帅</p>
<!--方式2:数组方式,同时引用多个样式-->
<p :class="[bb,dd]">帅高高真帅</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script>
new Vue({
el: "#box",
data:{
bb:'aa', //样式.aa作为值赋给bb
dd:'cc' //样式.cc作为值赋给dd
}
});
</script>
</body>
</html>
方式3:json形式绑定(******):直接通过json格式的方式,直接调用style中的样式,并且通过true 或 false来决定是否应用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>class属性绑定</title>
<style>
.aa{
color: red;
font-size: 20px;
}
.cc{
background-color: #ccc;
}
</style>
</head>
<body>
<div id="box">
<!--方式3: json形式,aa表示style中的.aa,值为true表示应用aa,false则不应用,常用!!!-->
<p :class="{aa:true,cc:true}">帅高高真帅</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script>
new Vue({
el: "#box",
data:{
}
});
</script>
</body>
</html>
在实际的应用中,是通过变量或者表达式来使用的:
<!--通过表达式或者变量在实际的场景中使用-->
<p :class="{aa:num>0,cc:flag}">帅高高真帅</p>
<!--变量引用json形式-->
<p :class="hello">帅高高真帅</p>
//vue实例中的data
data:{
flag:true,
num:3
hello:{aa:true,cc:true}
}
三、绑定style属性
3.1、绑定style属性
<body>
<div id="box">
<!--引用变量的方式-->
<p :style="xx"></p>
<!--引用数组的方式-->
<p :style="[xx,yy]"></p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script>
new Vue({
el: "#box",
data:{ //定义:style绑定的xx,yy的样式
xx:{color:"red",fontsize:"30px"},
yy:{backgroundColor:'#ccc'}
}
});
</script>
</body>

浙公网安备 33010602011771号