软糖

Vue2-3 event

Simple Example

Please look at this.$emit() method. and how we use it to notify the parent view.

Basically, the notification path is

input @blur -> applied method -> $emit applied event -> coupon @applied -> onCouponApplied method

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<body>
<div id="root">
<coupon @applied="onCouponApplied"></coupon>
<h1 v-if="couponApplied">You used a coupon</h1>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="./order.js"></script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Vue.component('coupon', {
template: `<input placeholder="Enter code" @blur="applied">`,
methods: {
applied() {
this.$emit('applied')
},
},
})
new Vue({
el: '#root',
data: {
couponApplied: false,
},
methods: {
onCouponApplied() {
this.couponApplied = true
},
}
})

Send/Listen event by shared instance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
window.Event = new Vue()
Vue.component('coupon', {
template: `<input placeholder="Enter code" @blur="applied">`,
methods: {
applied() {
Event.$emit('applied')
},
},
})
new Vue({
el: '#root',
data: {
couponApplied: false,
},
created() {
Event.$on('applied', () => alert('Handling'))
}
})