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
这些指令。
template
中v-slot指令应用
v-slot
在组件中使用slot
进行占位时,也是在slot
标签内使用name 属性给slot插槽定义一个名字。但是在html内使用时就有些不同了。需要使用template
模板标签,template
标签内,使用v-slot
指令绑定插槽名,标签内写入需要添加的内容。
示例代码如下:
<body>
<div id="app">
<Test>
<template v-slot:header="scope">//v-slot定义作用域插槽
<div>
<h3>slot</h3>
<p> {{scope.msg}} </p>
</div>
</template>
</Test>
</div>
<template id="test">
<div>
<slot name="header":msg="msg"></slot>
<p>这里是test组件</p>
</div>
</template>
</body>
<script>
Vue.component('Test',{
template:"#test",
data(){
return {
msg:'这里是头部'
}
}
});
new Vue({
}).$mount("#app")
</script>
Vue2.6.0
中使用v-slot
指令取代了特殊特性slot
与slot-scope
,但是从上述案例可以看出,v-slot
在使用时,需要在template
标签内,这点大家在应用时要注意。