Vue使用组件的细节点

一:is属性的使用:
例如:

<table>
				<tbody>
					<row></row>
					<row></row>
					<row></row>
				</tbody> 
			</table>
			<script>
			 Vue.component('row',{
				template:'<tr><td>this is a row</td></tr>'
			})
			</script>

在这里插入图片描述
这样浏览器解析时会出现bug,html5规范要求table中有tbody,tbody必须要有tr。tbody解析不了row就会出现这种情况,这时我们使用is属性可以解决这个问题。同样的,ul、ol、select标签也是一样的,它们的li或option如果要用到组件也可以使用is属性。

<table>
				<tbody>
					<tr is='row'></tr>
					<tr is='row'></tr>
					<tr is='row'></tr>
				</tbody>
			</table>

在这里插入图片描述
二: 子组件data的使用
在子组件直接把data写成对象的形式是不行的,如

<table>
				<tbody>
					<tr is='row'></tr>
					<tr is='row'></tr>
					<tr is='row'></tr>
				</tbody>
			</table>
		</div>
		<script>
			Vue.component('row',{
				data:{
					content:'this is content'
				},
				template:'<tr><td>{{content}}</td></tr>'
			})
		</script>

在这里插入图片描述
它说data应该是一个函数,我们这样写就可以了:

<script>
			Vue.component('row',{
				data:function(){
					return{
						content:'this is content'
					}
				},
				template:'<tr><td>{{content}}</td></tr>'
			})
</script>

这样用函数返回一个对象的原因是一个子组件可能会使用多次,而这样做的好处是可以使子组件之间的互不影响,每一个子组件都有一个独立的数据存储。
三:ref
虽然vue并不推荐我们直接操作dom,但是在某些情况下,我们不得不来操作dom,在vue中我们通过ref引用的形式来获取dom并操作dom
this.refs指当前整个vue实例里面所有的引用

<div 
				ref='hello'
				@click="handleClick"
				>Hello World</div>
		</div>

this.$refs.hello就是指的是上面这个div元素
下面这些是通过组件通信和ref实现了一个简单的计数器的功能

<body>
		<div id="root">
			<counter ref='one' @change='handleChange'></counter>
			<counter ref='two' @change='handleChange'></counter>
			{{total}}
		</div>
	</body>
	<script>
		Vue.component('counter',{
			template:'<div @click="handleClick">{{number}}</div>',
			data:function(){
				return{
					number:0
				}
			},
			methods:{
				handleClick:function(){
					this.number++;
					this.$emit('change')
				}
			}
		})
		var vm = new Vue({
			el:"#root",
			data:{
				total:0
			},
			methods:{
				handleChange:function(){
					this.total=this.$refs.one.number+this.$refs.two.number
				}
			}
			
		})
	</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值