1、条件渲染
在vue中,提供了条件渲染
- v-if
- v-else
- v-else-if
- v-show
1.1 v-if
v-if指令用于条件性地渲染一块内容。这块内容只会在指令的表达式返回true值的时候被渲染
<template>
<h3>条件渲染</h3>
<div v-if="flag">你能看见我吗</div>
<!-- <h1>你好啊</h1> -->
</template>
<script>
export default {
data() {
return {
flag: true,//flag为真时可以看见
}
}
}
</script>
1.2 v-else
你可以使用v-else为v-if添加一个else区块
<template>
<h3>条件渲染</h3>
<div v-if="flag">你能看见我吗</div>
<div v-else="flag">看不见我</div>
<!-- <h1>你好啊</h1> -->
</template>
<script>
export default {
data() {
return {
flag: false,//flag为假时出现v-else的看不见我
}
}
}
</script>
1.3 v-else-if
v-else-if提供的是相当于v-if的“else if”区块。它可以连续多次重复使用
<template>
<h3>条件渲染</h3>
<div v-if="type==='A'">A</div>
<div v-else-if="type==='B'">B</div>
<div v-else-if="type==='C'">C</div>
<div v-else>NO</div>
</template>
<script>
export default {
data() {
return {
flag: false,
type : "C",
}
}
}
</script>
1.4 v-show
另外一个可以用来按条件显示的元素指令时v-show。用法一样。只能判断自己本身的条件。
<template>
<h3>条件渲染</h3>
<div v-show="flag">你能看见我吗</div>
</template>
<script>
export default {
data() {
return {
flag: true,
type : "C",
}
}
}
</script>
v-if 和v-show
v-if 是“真实的”按条件渲染,因为他确保了在切换时,条件区块内的事件监听器和子组件都会被销毁和重建。
v-if 也有惰性的:如果在初次渲染时条件值为 false,则不会做任何事情。条件区块只有当条件首次变为true时才会被渲染。
相比之下,v-show 简单许多,元素无论初始条件如何,始终会被渲染,只有CSS display属性会被切换。
总的来说,v-if有更高的切换开销,而v-show有更高的初始渲染开销。因此,如果需要频繁切换,则使用v-show较好;如果在运行时绑定条件很少改变,则使用v-if会更合适。
2、列表渲染
可以使用一个 v-for 指令基于一个数组来渲染列表。v-for 指令的值需要使用item in items 形式的特殊语法,其中 items 是源数据的数组,而item是迭代项的别名。
<template>
<h2>列表渲染</h2>
<div>
<p v-for="item in names">{{ item }}</p>
</div>
</template>
<script>
export default {
data() {
return {
names: ["a", "b", "c", "d", "e"],//数组
}
}
}
</script>
复杂数据
大多数情况,我们渲染的数据来源于网路请求,也就是JSON格式
<template>
<h2>列表渲染</h2>
<p v-for="item in names">{{ item }}</p>
<div v-for="item in result">
<p >{{ item.title }}</p>
<img :src="item.avatar" alt="">
</div>
</template>
<script>
export default {
data() {
return {
names: ["a", "b", "c", "d", "e"],
result :[
{
"id":2299702,
"title": "my name is my name is my name is my name is my name y",
"avatar": "http://baidu.com/",
},
{
"id":229970223,
"title": "my name is my name is my name is my name is my name y",
"avatar": "http://baidu.com/",
},
{
"id":229970232,
"title": "my name is my name is my name is my name is my name y",
"avatar": "http://baidu.com/",
},
]
}
}
}
</script>
v-for 也支持可以使用可选的第二个参数表示当前选项的位置索引
<template>
<h2>列表渲染</h2>
<div>
<p v-for="(item,index) in names">{{ item }}-{{ index }}</p>
</div>
</template>
<script>
export default {
data() {
return {
names: ["a", "b", "c", "d", "e"],//数组
}
}
}
</script>
也可以使用 of 作为分割符来替代 in,这更接近JavaScript的迭代器语法。
v-for与对象
也可以使用 v-for 来遍历一个对象的所有属性。
<template>
<h2>列表渲染</h2>
<div>
<p v-for="(item,index) in names">{{ item }}-{{ index }}</p>
</div>
<div >
<p v-for="(item,key,index) of userInfor">{{ item }}-{{ key }}--{{ index }}</p>
</div>
</template>
<script>
export default {
data() {
return {
names: ["a", "b", "c", "d", "e"],//数组
userInfor:{
name:"西瓜",//对象
age:18,
sex:"男"
}
}
}
}
</script>