HTML5中的template标签
html5中template标签内容在页面中并不会显示。但是在后台查看页面DOM结构却存在template标签。这是因为template标签天生不可见,它设置了display:none;属性。
<!--当前页面只显示"我是自定义表现abc"这个内容,不显示"我是template",
这是因为template标签天生不可见-->
<template>
<div>我是template</div>
</template>
<abc>我是自定义表现abc</abc>
.vue 文件的基本结构如下:
<template>
........
</template>
<script>
export default {
name: "demo"
}
</script>
<style scoped>
.demo {
font-size: 28px;
}
</style>
上面template标签是用来写 html 模板的,且内部必须只有一个根元素,像下面这样(不然IDE会报错)
<template>
<div class="demo">
.....
</div>
</template>
但有时候我们也会看到,在template上使用for循环:
<template>
<div class="root">
<!--在template上使用for循环-->
<template v-for="item,index in 5">
<div>{{index}}---{{item}}</div>
</template>
</div>
</template>
下面我们一起通过浏览器dom渲染结果来看一下template是什么:
<template>
<div class="root">
<template>看看外面的标签是什么</template>
</div>
</template>
在浏览器中解析完的结果:
可以看到文字外面是 div.root 所以本质上的<template>标签并没有什么意义。template的作用是模板占位符,可帮助我们包裹元素,但在循环过程当中,template并不会被渲染到页面上.
我们继续看一下刚才的循环:
<template>
<div class="root">
<template v-for="(item,index) in 5">
<div>测试{{index}}</div>
</template>
</div>
</template>
浏览器解析后的效果:
不使用template,我们也可以这样写:
<template>
<div class="root">
<div v-for="item,index in 5">
<div>测试{{index}}</div>
</div>
</div>
</template>
但是这样循环出来会多出一层div来。
当我们不需要这外层的 div的时候,我们可以采用上面的方法,在 <template>标签上使用 v-for来循环。或者这样写:
<template>
<div class="root">
<div v-for="item,index in 5" :key="index">测试{{index}}</div>
</div>
</template>
注意
vue实例绑定元素内部的template标签不支持v-show指令,即v-show="false"对template标签来说不起作用。但是此时的template标签支持v-if、v-else-if、v-else、v-for这些指令。