一: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>