在vue中有内置事件click、mouseover等事件,同时我们还可以自定义一个事件 。事件名最好都是小写,或可用“—”进行分割命名,否则可能无效。如:my-event。我们还可以通过自定义事件进行子组件 —> 父组件传递数据。
直接看下面这个例子
1.自定义了一个组件<button-counter>
2.自定义了一个increment事件,在事件中调用了incrementTotal方法
3.调用内置点击事件click,注意在这里:@click.native,后面加上了.native。它表示调用内置事 件click,所以我们不难看出在自定义组件中要想调用内置事件,就必须加上.native
<button-counter @increment="incrementTotal" @click.native="show"></button-counter>
那么该怎么触发自定义事件呢? ,接着往下看
自定义组件:
这里我们主要看这一段代码(它触发了自定义事件):this.$emit('increment',val,!this.bool);
解释:触发自定义事件"increment",并传递了2个值(val、!this.bool),这2个参数将传递给incrementTotal()方法
//自定义组件
Vue.component('button-counter', {
//点击button调用组件内的incrementHandler()
template: '<button v-on:click="incrementHandler(5)">{{ counter }}</button>',
//数据
data: function () {
return {
counter: 0,
bool : true
}
},
//方法
methods: {
incrementHandler(val) {
this.counter += 1;
//触发它的父级的事件,即<button-counter>中的increment事件,并传递值val和一个boolean值
this.$emit('increment',val,!this.bool);
this.bool = !this.bool
}
},
})
整体代码:
<div id="app">
<div id="counter-event-example">
<p>{{ total }}</p>
<!--
increment是一个自定义事件(像click、mouseover等这样的事件)
这个事件将调用incrementTotal()
-->
<!--此时组件想要调用原生事件,如:@click.native加上native-->
<button-counter @increment="incrementTotal" @click.native="show"></button-counter>
<input type="checkbox" :checked="checked">
</div>
</div>
<script>
//自定义组件
Vue.component('button-counter', {
//点击button调用组件内的incrementHandler()方法
template: '<button v-on:click="incrementHandler(5)">{{ counter }}</button>',
data: function () {
return {
counter: 0,
bool : true
}
},
methods: {
incrementHandler(val) {
this.counter += 1;
//触发它的父级的事件,即<button-counter>中的increment事件,并传递值val和一个boolean值
this.$emit('increment',val,!this.bool);
this.bool = !this.bool
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0,
checked:true
},
methods: {
incrementTotal(val,b) {
this.total += val;
this.checked = b;
},
show(){
alert("点击事件触发")
}
}
})
</script>