v-if
作用和v-show一样,都是实现了元素的隐藏和显示,通过布尔值进行设置。
案例:
<!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>
<!-- 引入vue工具脚本 -->
<script src="js/vue2.js"></script>
</head>
<body>
<!-- 定义控制区域 -->
<div id="box">
<!-- 添加按钮控制信息的展示或隐藏 -->
<button @click="show()">显示/隐藏</button>
<br/>
信息展示:
<p v-if="isShow">我叫张无忌,明教教主</p>
</div>
<!-- 自定义脚本 -->
<script>
// 创建实例
var vm = new Vue({
el: '#box',
data: {
isShow: false
},
methods: {
show(){
// 切换布尔值的内容
// 每次进入到当前的函数之后进行布尔值的取反操作
this.isShow = !this.isShow
}
},
})
</script>
</body>
</html>
需要注意:如果将v-if中的值设置为了false,则页面中清除了当前的元素(删除了这个元素)
v-for
将容器中的所有数据进行循环遍历绑定到页面进行渲染的指令。类似于JavaScript中的for循环
语法
<标签名 v-for="(每次循环得到的数据,索引值) in 集合或数组名称"></标签名>
案例:
<!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>
<!-- 引入vue工具脚本 -->
<script src="js/vue2.js"></script>
</head>
<body>
循环遍历绑定数组中的对象
<!-- 定义控制区域 -->
<div id="box">
<!-- 循环遍历将数组中的内容绑定到ul无序列表中 -->
<h3>用户名称列表:</h3>
<ul>
<!-- li元素中进行循环遍历 -->
<li v-for="(item, index) in arrs">
<!-- 元素信息绑定 -->
{{index}} -- {{item}}
</li>
</ul>
</div>
<!-- 自定义脚本 -->
<script>
// 创建实例
var vm = new Vue({
el: '#box',
data: {
arrs: ['张三丰', '张无忌', '赵敏', '灭绝师太', '金毛狮王']
},
})
</script>
</body>
</html>
循环遍历数组中的脚本
<!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>
<!-- 引入vue工具脚本 -->
<script src="js/vue2.js"></script>
</head>
<body>
<!-- 定义控制区域 -->
<div id="box">
<!-- 循环遍历将数组中的内容绑定到ul无序列表中 -->
<h3>用户名称列表:</h3>
<ul>
<!-- li元素中进行循环遍历 -->
<!-- <li v-for="(item, index) in arrs">
{{index}} -- {{item}}
</li> -->
<li v-for="(item, index) in arrs"<!-- 元素信息绑定 -->
{{index}} -- {{item.name}} || {{item.loc}}
</li>
</ul>
</div>
<!-- 自定义脚本 -->
<script>
// 创建实例
var vm = new Vue({
el: '#box',
data: {
// arrs: ['张三丰', '张无忌', '赵敏', '灭绝师太', '金毛狮王'] // 单独的名称
arrs: [
{
name: '张三丰',
loc: '武当山'
},
{
name: '张无忌',
loc: '光明顶'
},
{
name: '赵敏',
loc: '峨眉山'
},
{
name: '灭绝师太',
loc: '峨眉山'
},
{
name: '金毛狮王',
loc: '冰火岛'
} // 每一个大括号就是一个对象
] // 可以在数组中管理对象(用大括号括起来的内容
},
})
</script>
</body>
</html>