Vue 常见的指令 v-if, v-show 与v-for

v-if , v-show 都是操作元素是否显示的指令,(其对应数据项的值为 true 或者 false)。但实现方法不一样,v-if 是从dom中删掉该元素(注释),而v-show是将该元素的display 属性设置为none。

相比较来说,频繁操作时v-show 性能更高一些,偶尔操作时v-if更好一些。

下例,显示或隐藏一个div:

<!DOCTYPE html>
<html>
<head>
	<title>v-if,v-show,v-for</title>
	<meta charset="utf-8">
	<script src="./vue.js"></script>
</head>
<body>
	<div id="root">
		<div v-if="show">hello world</div>
		<div v-show="show">hey hey hey</div>
		<button @click="handleclick">toggle</button>
		
	</div>

	<script >
		new Vue({
			el: "#root",
			data: {
				show: true
			},
			methods: {
				handleclick: function(){
					this.show = !this.show;
				}
			}
		})
	</script>
</body>
</html>

v-for 指令,通过一组数据,循环显示页面上的dom结构。

其中key标签,使得查询的速度更快,但其不能有重复项。

下例:

<!DOCTYPE html>
<html>
<head>
	<title>v-if,v-show,v-for</title>
	<meta charset="utf-8">
	<script src="./vue.js"></script>
</head>
<body>
	<div id="root">
		<div v-if="show">hello world</div>
		<div v-show="show">hey hey hey</div>
		<button @click="handleclick">toggle</button>
		<ul>
			<!-- <li v-for="item of list">{{item}}</li> -->
			<li v-for="(item,index) of list" :key="index">{{item}}</li>
		</ul>
		
	</div>

	<script >
		new Vue({
			el: "#root",
			data: {
				show: true,
				list: [100,200,300]
			},
			methods: {
				handleclick: function(){
					this.show = !this.show;
				}
			}
		})
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/purple_lumpy/article/details/81156620
今日推荐