v-if,v-show和v-for指令

点击按钮隐藏或者显示按钮以上的内容:

<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-if,v-show,v-for指令</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<div v-if="show">hello world</div>//将此处的v-if换成v-show表现效果没有发生改变
<button @click="handClick">toggle</button>
</div>
 
<script>
new Vue({
el:"#root",
data:{
show:true
},
methods:{
handClick:function(){
this.show=!this.show;
}
}
})
</script>
</body>
</html>
v-if和v-show的差别可以通过控制台查看
 
v-for的作用是当你有一个数据,需要做循环展示,每一个标签都可以展示出一个<li>标签,但是需要注意的是,在用v-for做循环展示的时候,需要定义一个key值来提高展示的效率,一下代码中的key值是item
并且每一项数据的key值都要不相同,以下戴安每一次的循环值分别是1,2,3,满足条件
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-if,v-show,v-for指令</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<div v-if="show">hello world</div>
<button @click="handClick">toggle</button>
<ul>
<li v-for="item of list":key="item">{{item}}</li>
</ul>
</div>
 
<script>
new Vue({
el:"#root",
data:{
show:true,
list:[1,2,3]
},
methods:{
handClick:function(){
this.show=!this.show;
}
}
})
</script>
</body>
</html>
若循环key值是1,1,2,(有两个key值相同),以下的index表示每一项的下标
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-if,v-show,v-for指令</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="root">
<div v-if="show">hello world</div>
<button @click="handClick">toggle</button>
<ul>
<li v-for="(item,index) of list":key="index">{{item}}</li>
</ul>
</div>
 
<script>
new Vue({
el:"#root",
data:{
show:true,
list:[1,1,3]
},
methods:{
handClick:function(){
this.show=!this.show;
}
}
})
</script>
</body>
</html>
其实index并不是一个也别好的选择,如果需要频繁地对列表进行变更的时候,使用index是存在问题的

posted on 2018-08-20 10:58  超级爱学习的小菜鸟  阅读(152)  评论(0)    收藏  举报

导航