vue中template标签的用法

1,867 阅读1分钟

一、前言

  • template标签的作用是模板占位符,可帮助我们包裹元素,但在渲染过程当中,template不会被渲染到页面上
  • html中的template标签中的内容在页面中不会显示。但是在后台查看页面DOM结构存在template标签。这是因为template标签天生不可见,它设置了display:none;属性。

二、用法

1、可见性

  • template作为根元素时默认内容可见,只能有一个根元素否则报错。
<template>
  <div class="box">
    一段文字
  </div>
</template>
  • template作为标签时的内容默认是不可见的
<template>
  <div class="box">
    一段文字
    <template>
      <div>一段文字1</div>
      <div>一段文字2</div>
    </template>
  </div>
</template>
  • 可以添加v-if="true"使内容可见
<template>
  <div class="box">
    一段文字
    <template v-if="true">
      <div>一段文字1</div>
      <div>一段文字2</div>
    </template>
  </div>
</template>

2、使用v-for

  • 在外层不想或不方便使用div时使用template实现渲染
<template>
  <div class="box">
    <template v-for="item in list">
      <div>这段文字可见{{ item }}</div>
    </template>
  </div>
</template>

3、使用v-slot

  • 子组件定义插槽
<template>   
    <div> 
        <slot name="header":msg="msg"></slot> 
        <p>这里是test组件</p> 
    </div> 
</template>
  • 父组件通过template定义内容
<template>   
    <div id="app"> 
        <Test> 
            <template v-slot:header="scope">//v-slot定义作用域插槽 
                <div> 
                    <h3>slot</h3> 
                    <p> {{scope.msg}} </p> 
                </div> 
            </template> 
        </Test> 
    </div>
</template>