自定义组件绑定原生事件+动态组件
1. 给自定义组件绑定原生事件
在实际开发中,直接给DOM标签元素添加原生事件是没有问题的,但是给自定义组件直接添加原生事件就会失效,因为Vue对于自定义组件有一套自己的系统相当于设置了规则,那么直接监听自定义组件的根元素上的一个原生事件如何实现?.native 修饰符 ,只作用于自定义的组件标签
< child>是自定义组件标签绑定的是自定义事件,template中的 < div>上绑定的是原生事件,因为div是DOM元素。而当子组件想触发父组件的事件监听使用this.$emit(‘父组件事件名’)实现,如下:
但是这时太复杂,我们可能需要直接就实现监听根元素的原生事件?可以直接在< child @click.native=‘事件名’>利用native来实现绑定原生事件。等同于在子组件中利用 this.$emit(‘click’)处理click事件再向父组件发送click事件。
2. 动态组件
需求:Vue有一个< component>内置动态组件标签,现希望实现鼠标点击时可以动态切换组件。< component>>+ :is 动态的改变组件名.
< component :is=“type” ></ component>可以等价:
< child-one v-if="type=== ‘child-one’ "></ child-one>
< child-two v-if="type ===‘child-two’ "></ child-two>
注:v-if对于频繁切换操作来说会降低性能,所以若是频繁切换建议使用v-show。
<div id="root">
<component :is="type" ></component>
<button @click="handleBtnClick"></button>
</div>
<script>
Vue.component('child-one', {
template: `<div>child-one</div>`
})
Vue.component('child-two', {
template: `<div>child-two</div>`
})
var vm= new Vue({
el: '#root',
data: {
type: 'child-one'
},
methods: {
handleBtnClick: function() {
this.type = this.type==='child-one'?'child-two':'child-one';
}
}
})
</script>