这次给大家带来vue.js中v-on事件使用详解,vue.js中v-on事件使用的注意事项有哪些,下面就是实战案例,一起来看一下。
每个 vue 实例都实现了事件接口(events interface),即:
使用 $on(eventname) 监听事件
使用 $emit(eventname) 触发事件
vue的事件系统分离自浏览器的eventtarget api。尽管它们的运行类似,但是$on 和 $emit 不是addeventlistener 和 dispatchevent 的别名。
另外,父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。
下面是一个文档上面的例子:
2017年4月11日更新
<p id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementtotal"></button-counter>
<button-counter v-on:increment="incrementtotal"></button-counter>
</p>
vue.component('button-counter', {
template: '<button v-on:click="increment">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1
this.$emit('increment')
}
},
})
new vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementtotal: function () {
this.total += 1
}
}
})
步骤1:
大家先看到这里,其实在步骤4里面的自定义标签经过渲染之后是变成了如 步骤一
一样的代码,所以我们应该从这里入手理解父子组件间事件绑定。在子组件里面把点击事件(click)绑定给了函数increment(即图片里面的步骤2),这里容易理解,即点击了子组件的按钮将会触发位于子组件的increment函数
步骤2与步骤3:
increment函数被触发执行,在步骤2里面执行了一句调用函数的语句
this.$emit('increment')
我们来看一下文档
vm.$emit( event, […args] ) : 触发当前实例上的事件。附加参数都会传给监听器回调
在这里是什么意思呢?按我自己的大白话就是这样说的:
通过这句函数可以让父组件知道子组件调用了什么函数,this.$emit(‘increment') 即类似于子组件跟父组件说了一声“hi,爸爸 我调用了我自己的increment函数”,通知父组件
步骤4:
回看一下在父组件里面定义的自定义标签,可以看到
v-on:increment=incrementtotal
什么意思呢?我们还是用大白话来解释一下
就是说“孩子,当你调用了increment函数的时候,我将调用incrementtotal函数来回应你”
这时我们回想步骤3,在子组件我们已经使用emit来进行通知,所以,这样就形成父子组件间的相互呼应传递信息,其实在开发的过程中父子组件通讯也都是使用这样的方法,父组件传递信息给子组件的时候会通过props参数,通常不会直接在子组件中修改父组件传递下来的信息,而且通过这样的一个钩子去通知父组件对某些参数进行改变
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
js匿名函数应该怎样使用
nodejs基于ffmpeg进行视频推流直播
vue2.0设置全局样式步奏详解
以上就是vue.js中v-on事件使用详解的详细内容。