$emit 触发当前实例上的事件,也可以简单的理解为触发父组件上的事件(向上冒泡),实例(当前实例)如下:
<!DOCTYPE html><html> ???<head> ???????<meta charset="UTF-8"> ???????<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> ???????<title>session</title> ???????<script src="https://unpkg.com/vue/dist/vue.js"></script> ???????<style type="text/css"> ???????????#session { ???????????????width: 600px; ???????????????margin: 0 auto; ???????????????text-align: center; ???????????} ???????</style> ???</head> ???<body> ???????<div id="counter-event-example"> ?????????<button-counter v-on:increment="incrementTotal"></button-counter> ???????</div> ???????????????<script> ???????????Vue.component(‘button-counter‘, { ?????????????template: ‘<button v-on:click="incrementCounter">点我哒</button>‘, ?????????????methods: { ???????????????incrementCounter: function () { ???????????????????alert("我是组件"); ?????????????????????this.$emit(‘increment‘) ???????????????} ?????????????} ???????????}) ???????????????????????new Vue({ ?????????????el: ‘#counter-event-example‘, ?????????????methods: { ???????????????incrementTotal: function () { ???????????????????alert("我是当前实例"); ???????????????} ?????????????} ???????????}) ???????</script> ???</body></html>
当点击“点我哒”的时候,会依次跳出下面两个 alert,根据前后跳出的顺序我们可以清楚的看到事件的前后触发顺序,如图:
这样是不是就很清楚的理解 $emit 的作用了,:)
vue.js学习笔记(3)— $emit 作用快速了解
原文地址:https://www.cnblogs.com/zxn-9588/p/8969014.html