Class与Style的绑定*
操作元素的 class 列表和内联样式是数据绑定的一个常见需求。因为它们都是 attribute,所以我们可以用 v-bind 处理它们:只需要通过表达式计算出字符串结果即可。不过,字符串拼接麻烦且易错。因此,在将 v-bind 用于 class 和 style 时,Vue.js 做了专门的增强。表达式结果的类型除了字符串之外,还可以是对象或数组。
1.我们给v-bind:class传一个对象,以动态的形式切换class,代码如下,
<div :class=“{active:isActive}”>, isActive是布尔值, if(isActive==true)div的类就是active,反之,div的类为空。
2.我们给v-bind:class传一个数组,以动态的形式切换class,当这个数组是常量数组的时候代码如下 ,
3.我们将v-for和v-bind结合使用,代码如下
4.将v-bind动态绑定style对象,代码如下
我是中国人
5.将v-bind动态绑定style数组,数组的属性是对象,代码如下
niaho
6.我对vue对象的理解,代码上的注释说明如下
!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>
<style>
* {
padding: 0px;
margin: 0px;
}
.hover {
background: red;
}
</style>
</head>
<body>
<div id="app">
<ul>
<!-- getIndex(index);调用this指向下的函数,并传参 -->
<li v-for="(item,index) in getPlace()" v-bind:key="index" v-on:click="getIndex(index)"
v-bind:class="currentIndex==index?'hover':'' ">{{index}}--{{item}}</li>
</ul>
</div>
<script src="vue.js"></script>
<script>
const vueObj = new Vue({
el: "#app",
data() {
return { //data方法里面返回值,这里面是返回对象,新的对象里面有新的方法,新的方法有新的返回值,此时的返回值就是arr数组数据,vueObj是顶级对象,this指向顶层对象,this.{data().该方法里面返回的对象},this.currentIndex,this.返回的对象里面的方法,this.getPlace()
currentIndex: 0,//this指向方法里面返回的对象,this.currentIndex
getPlace() {
currentIndex = 0; //this指向的是该函数,指向不到currentIndex
const arr = ["武汉", "北京", "猫和老鼠"];
console.log(this); //就是最大的顶层对象vueObj
return arr;
}
}
},
methods: {
getIndex(inde) {
console.log(inde);
this.currentIndex = inde
}
}
})
</script>
</body>
</html>```