Vue:子组件使用的细节,子组件中的data,ref的使用,

我们创建一个table

<div id="app">
	<table>
		<tbody>
			<row></row>
			<row></row>
			<row></row>
		</tbody>
	</table>
</div>

我们希望每一行的数据是子组件

<script>
	Vue.component('row', {
		template:'<tr><td>this is a row</td></tr>'
	})
	var app = new Vue({
		el:"#app",
	})
</script>

在这里插入图片描述
正常来说3个tr会在tbody里面,这里出错了,这是为什么呢
在H5的规范中,tbody下是tr,我们在使用子组件的时候,这里的tr写成了row,所以会出现问题,这个时候我们可以使用Vue提供的is属性来解决这个问题

<div id="app">
			<table>
				<tbody>
					<tr is="row"></tr>
					<tr is="row"></tr>
					<tr is="row"></tr>
				</tbody>
			</table>
		</div>

在这里插入图片描述
这样就没问题了
其他标签比如ul下的li,ol下的li,select下的option也可以使用is属性解决模板出现的bug问题

2.在子组件中,data必须是个函数,不能为对象

<div id="app">
			<table>
				<tbody>
					<tr is="row"></tr>
					<tr is="row"></tr>
					<tr is="row"></tr>
				</tbody>
			</table>
		</div>
		<script>
			Vue.component('row', {
				data: function() {
					return {
						content:'this is content'
					}
				},
				template:'<tr><td>{{content}}</td></tr>'
			})
			var app = new Vue({
				el:"#app",
			})
		</script>

之所以这样设计,是因为子组件不像根组件,只会被调用一次,我们不希望子组件之间的数据产生冲突,或者说,每个子组件都应该有自己的数据

3.ref的使用

<div id="app">
			<div ref='hello' @click="hdclick">
				hello box
			</div>
		</div>
		<script>
			var app = new Vue({
				el:"#app",
				methods:{
					hdclick: function(){
						console.log(this.$refs.hello.innerHTML);
					}
				}
			})
		</script>

在这里插入图片描述
使用ref获取div的dom节点
当ref为组件上的ref时,获取的为组件的引用

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值