十一、computed的使用
computed可以对属性进行计算,只有在属性发生变化时才会被触发,会大大提升效率。计算属性一定要有返回值return。
method方法执行时,所有的方法都会执行,效率会下降。
<button @click="a++">加A</button>
<button @click="b++">加B</button>
<p>A--{{AddToA}}</p>
<p>B--{{AddToB}}</p>
computed: {
AddToA() {
console.log("A++");
return this.a + this.age;
},
AddToB() {
console.log("B++");
return this.b + this.age;
}
}
十二、动态绑定CSS
<button v-on:click="nearby = !nearby">Toggle nearby</button>
<button v-on:click="available = !available">Toggle available</button>
<div v-bind:class="compClasses">
<span>Ryu</span>
</div>
computed: {
compClasses: function(){
return{
available: this.available,
nearby: this.nearby,
}
}
}
十三、v-if和v-show
v-if
data() {
return {
error: false,
success: false
};
}
<button @click="error = !error">error</button>
<button @click="success = !success">success</button>
<p v-if="error">error显示</p>
<p v-else-if="success">success显示</p>
<p v-else>others</p>
v-show
<p v-show="error">show:error</p>
v-if和v-show的区别是,v-if为false时,整个p标签都不存在,v-show的p标签是存在的
十四、v-for
data() {
return {
characters: ["小张", "小徐", "小李", "小王"],
users: [
{ name: "小张", age: 28 },
{ name: "小徐", age: 32 },
{ name: "小李", age: 11 },
{ name: "小王", age: 45 }
]
};
}
<ul>
<li v-for="(char,index) in characters">
{{index}}. {{char}}
</li>
</ul>
<ul>
<li v-for="(user,index) in users">
{{index}}.{{user.name}}-{{user.age}}
</li>
</ul>
<ul>
<div v-for="(user,index) in users">
<li v-for="(val,key) in user">
{{key}}.{{val}}
</li>
</div>
</ul>
网友评论