关于 template 标签 在 js vue 中的用法

template 定义

内容模板 <template> 元素是一种用于保存客户端内容机制,该内容在加载页面时不会呈现。
将模板视为一个可存储在文档中以便后续使用的内容片段。虽然解析器在加载页面时确实会处理<template>元素的内容,但这样做只是为了确保这些内容有效;但元素内容不会被渲染。

说白了和input type=”hidden” 类似,一个储存字符状态,一个储存代码片段

js 中使用

IE完全不兼容,仅作为了解扩展!

<table id="producttable">
		  <thead>
		    <tr>
		      <td>UPC_Code</td>
		      <td>Product_Name</td>
		    </tr>
		  </thead>
		  <tbody>
		    <!-- 现有数据可以可选地包括在这里 -->
		  </tbody>
		</table>
		<input type="hidden" name="" id="" value="123123" />
		<template id="productrow">
		  <tr>
		    <td class="record"></td>
		    <td></td>
		  </tr>
		</template>


// 通过检查来测试浏览器是否支持HTML模板元素
		// 用于保存模板元素的内容属性。
		if ('content' in document.createElement('template')) {
		debugger
		  // 使用现有的HTML tbody实例化表和该行与模板
		  let t = document.querySelector('#productrow'),
		  td = t.content.querySelectorAll("td");
		  td[0].textContent = "1235646565";
		  td[1].textContent = "Stuff";
		
		  // 克隆新行并将其插入表中
		  let tb = document.getElementsByTagName("tbody");
		  let clone = document.importNode(t.content, true);
		  tb[0].appendChild(clone);
		
		  // 创建一个新行
		  td[0].textContent = "0384928528";
		  td[1].textContent = "Acme Kidney Beans";
		
		  // 克隆新行并将其插入表中
		  let clone2 = document.importNode(t.content, true);
		  tb[0].appendChild(clone2);
		
		} else {
		  // 找到另一种方法来添加行到表,因为不支持HTML模板元素。
		}

vue中使用

使用就可以配合使用v-for v-if来节约不必要的层级,来增加代码的可读性。
在vue中使用外层 的时候必须要嵌套一个根元素,否者报错。

V-for的使用
<div class="asd" style="font-size: 0.5rem;">
	<template v-for="item,index in people" >
		<div>测试{{index}}</div>
	</template>
</div>
V-if的使用
为了具体的体现,我层级嵌套的比较多。
//男1 女0
			<template v-for="(item,value) in people">
				<view class="asd" style="font-size: 0.5rem;">
					<template v-if="item.sex==1">
						<view class="isBlue">
							<template v-if="item.age<18">
								{{item.name}}未成年
							</template>
							<template v-else>
								{{item.name}}已成年
							</template>
						</view>
					</template>
					<template v-else>
						<view class="isRed">
							<template v-if="item.age<18">
								{{item.name}}未成年
							</template>
							<template v-else>
								{{item.name}}已成年
							</template>
						</view>
					</template>
				</view>
			</template>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值