给组件绑定原生事件
<item-todo @change="handleClick"></item-todo>
Vue.component('item-todo', {
template: '<div @click="handleDiv">hello</div>',
methods:{ //绑定在Dom元素上的事件为原生事件
handleDiv:function(){
this.$emit('change')
}
}
})
var vm= new Vue({
el: '#app',
methods:{
handleClick:function(){
alert('click')
}
}
})
组件上绑定的 change 事件是一个自定义事件。 组件上自定义事件的触发: this.$emit.
<item-todo @click.native="handleClick"></item-todo> //监听组件的原生事件 .native
动态组件和 v-once
<div id="todo-list-example">
<child-one v-if="type3 === 'child-one'"></child-one>
<child-two v-if="type3 === 'child-two'"></child-two>
<button @click="handleClick">切换</button> //通过 v-if 来切换组件
</div>
<script>
Vue.component('child-one', {
template: '<div v-once>child-one</div>'
})
Vue.component('child-two', {
template: '<div v-once>child-two</div>'
}) //v-once 指令会将内容放在内存里,能够有效提高静态内容的展示效率
new Vue({
el: '#todo-list-example',
data: {
type3: 'child-one'
},
methods: {
handleClick: function () { //三元运算符
this.type3 = this.type3 == 'child-one' ? 'child-two' : 'child-one'
}
}
})
</script>
上面的方式是通过 v-if 指令来进行两个组件间的切换,下面是 Vue 提供的更简便的方式。 <component :is="type3">
<div id="todo-list-example">
<component :is="type3"></component> //会通过 type3 的值,渲染对应命名的子组件
<button @click="handleClick">切换</button>
</div>
<script>
Vue.component('child-one', {
template: '<div>child-one</div>'
})
Vue.component('child-two', {
template: '<div>child-two</div>'
})
new Vue({
el: '#todo-list-example',
data: {
type3: 'child-one'
},
methods: {
handleClick: function () {
this.type3 = this.type3 == 'child-one' ? 'child-two' : 'child-one'
}
}
})
</script>