给一个子组件定义自定义事件的步骤大致如下:
-
在父组件中使用
v-on绑定自定义事件,并定义回调。例如给一个
user-info绑定自定义事件:1<!-- 2 App.vue 3 --> 4 5<template> 6 <div> 7 <!-- 8 通过父组件给子组件绑定一个自定义事件 9 实现子组件给父组件传递数据 10 使用 .once 修饰符,让事件只在第1次被触发时执行回调 11 --> 12 <user-info @get-name.once="getUserName"/> 13 </div> 14</template> 15 16<script> 17 import UserInfo from './components/user-info.vue'; 18 19 export default { 20 name: 'app', 21 components: { 22 UserInfo 23 }, 24 methods: { 25 getUserName(name) { 26 console.log( 27 'The event get-name has be trigged.'); 28 }, 29 }, 30 } 31</script> -
然后在子组件中,触发该自定义事件。
接上例:
1<!-- 2 user-info.vue 3--> 4 5<template> 6 <div class="user"> 7 <h2>用户姓名:{{name}}</h2> 8 <h2>用户年龄:{{age}}</h2> 9 <h2>用户性别:{{sex}}</h2> 10 <button @click="sendUserName">获取用户姓名</button> 11 </div> 12</template> 13 14<script> 15 16export default { 17 name: 'user-info', 18 data() { 19 return { 20 name: '张三', 21 sex: '男', 22 age: 21, 23 } 24 }, 25 methods: { 26 sendUserName() { 27 // 触发 user-info 组件实例上的 get-name 事件 28 this.$emit('get-name') 29 }, 30 }, 31} 32</script>
实现子组件到父组件的数据通信
通过自定义事件,可以实现子组件到父组件的数据通信。
如上例,在子组件user-info中,触发get-user-name事件的方法为this.$emit()(this是组件实例,Vue实例上也有这个方法)。
this.$emit():
- 参数1:触发的事件名称。
- 参数2 ~ n:触发事件的同时,向父组件传递的数据。
子组件通过调用this.$emit()来触发事件,然后告知父组件有数据需要传递。接着通过this.$emit()的第2 ~ n个参数,将数据传递给父组件。
父组件通过事件回调函数来处理事件,并接收从子组件传递过来的数据。
例如某个子组件触发了update事件,并且将数据传递给父组件:
1this.$emit("update", this.name, this.sex, this.age)
在父组件的methods中,可以这样定义回调函数:
-
定义对应的形参:
1updateHandler(name, sex, age) { 2 /* ... */ 3} -
定义数量可变的形参:
1updateHandler(...params) { 2 /* ... */ 3}
修改上方的user-info和App组件,从user-info中获取用户的姓名,并在App组件中显示欢迎消息:
1<!--
2 App.vue
3 -->
4
5<template>
6 <div class="app">
7 <h1>{{msg}}</h1> <hr>
8 <user-info @get-name="getUserName"/>
9 </div>
10</template>
11
12<script>
13 import UserInfo from './components/user-info.vue';
14
15 export default {
16 name: 'app',
17 components: {UserInfo},
18 data() {
19 return {
20 userName: '',
21 }
22 },
23 computed: {
24 msg() {
25 return `Hello ${this.userName}!`
26 },
27 },
28 methods: {
29 getUserName(name) {
30 console.log(
31 'The event get-name has be trigged.', name);
32 this.userName = name
33 },
34 },
35 }
36</script>
37
38<style>
39.app {
40 background-color: orange;
41 padding: 5px;
42}
43</style>
1<!--
2 user-info.vue
3 -->
4
5<template>
6 <!-- ... -->
7</template>
8
9<script>
10export default {
11 name: 'SiteUser',
12 data() {
13 /* ... */
14 },
15 watch: {
16 name: {
17 immediate: true,
18 handler() {
19 // 触发 user-info 组件实例上的 get-name 事件,并传递数据
20 this.$emit('get-name', this.name)
21 }
22 }
23 },
24}
25</script>
26
27<style scoped>
28.user {
29 background-color: skyblue;
30 padding: 5px;
31 margin-top: 30px;
32}
33</style>
绑定自定义事件
事件有两种绑定方式:
-
使用
v-on指令绑定。如上所示的案例,都是使用
v-on来绑定自定义事件。 -
在父组件中,使用
ref属性获取组件实例对象,然后通过在父组件的mounted()钩子中调用组件实例对象的$on方法绑定。1<demo @event-name="eventHandler"/>上方对应的使用
ref绑定事件的方法是:1<demo ref="demo"/>1mounted() { 2 this.$ref.demo.$on('event-name', this.eventHandler) 3}使用
ref加mounted绑定事件的好处是,自定义度高。例如可以在mounted中使用定时器来实现延迟绑定事件的效果。注:
在Vue实例对象或组件实例对象上,要让绑定事件仅触发一次,可以使用
this.$once()。this.$once()的参数与this.$on()一致。在
mounted中,如果要在绑定事件的同时定义回调函数,应该使用Lambda表达式:1mounted() { 2 this.$ref.demo.$on('event-name', (...params) => { 3 /* ... */ 4 }) 5}这是因为,如果使用一般的
function来定义,那么回调函数中的this指向的是demo的组件实例对象;而使用Lambda来定义,回调函数中的this指向的就是当前的组件实例对象。如果
this.$ref.demo.$on()传入的回调函数是methods中定义的函数,那么这个函数需要使用function来定义。也就是说,在绑定自定义事件回调时,回调函数要么是配置在
methods中用function定义,要么用Lambda表达式定义。如果子组件的
this.$emit()是在immediate:true的watch中调用的,那么就不要使用ref来绑定。因为immediate:true的watch是在beforeCreate()之后created()进行第1次执行。
解绑自定义事件
解绑自定义事件使用的是this.$off()方法:
this.$off(event):解绑event指定的事件。event是事件的名称,字符串类型。this.$off([event1, event2, ...]):解绑数组中指定的多个事件。event1、event2等均是事件的名称,字符串类型。this.$off():解绑所有的自定义事件。当this.$off()没有附带任何参数直接调用时,this.$off()会将实例中的所有事件解绑。
解绑自定义事件后,无论再调用多少次对应的this.$emit(),事件都不会被触发。除非在父组件中再次绑定这些自定义事件。
绑定原生事件
Vue中,在组件标签上使用v-on指令绑定的事件,对组件来说,绑定的都是自定义事件。即使绑定的事件名称是原生事件的名称,Vue也会将其识别为自定义事件。
如果要在组件上绑定原生事件,可以使用.native修饰符。
例如:
1<demo @click.native="clickDemo">
全局事件总线
全局事件总线(Global Event Bus)是一种组件间通信的方式,适用于任意组件间通信。
全局事件总线是指,抽取出一个专门用来绑定和触发自定义事件的对象。所有的组件都通过在这个对象上绑定或触发自定义事件来接收或发送数据。
作为全局事件总线,需要满足以下条件:
-
能被所有组件访问。
可以将全局事件总线对象在Vue原型对象上,让所有组件都能访问。
-
拥有
$on、$emit和$off等方法。可以使用Vue实例或组件实例作为全局事件总线。
全局事件总线最适用于同级组件间的通信和跨越多层级的组件间的通行。
安装全局事件总线
一般情况下,是将main.js中的Vue实例对象作为全局事件总线对象,并且将Vue实例安装在Vue原型对象Vue.prototype上。
1new Vue({
2 /* ... */
3 beforeCreate() {
4 Vue.prototype.$bus = this // 安装全局事件总线
5 },
6 /* ... */
7}).$mount('#app')
$bus只有在Vue实例创建之前进行安装,才能生效。如果在new Vue()执行结束之后安装,是无法生效的(即$bus === undefined)。
使用事件总线发送数据
1this.$bus.$emit(event, this.eventHandler)
this指的是Vue组件实例(下同)。
使用事件总线接收数据
1this.$bus.$on(event, value1[, value2[, ...]])
关闭数据通道
在当前组件实例中,如果要在事件总线中关闭某条数据通道(停止某个自定义事件的数据发送和接收),可以使用$bus.$off()解绑某个事件。
1// 关闭单个通道
2this.$bus.$off(event)
3
4// 关闭多个通道
5this.$bus.$off([event1, event2, ...])
关闭数据通道(自定义事件)的同时,需要注意该通道(自定义事件)没有被其它组件或组件实例对象所使用。如果当前组件有多个实例,但是它们有相同的数据通道,最好是不要随便去关闭通道。
销毁前解绑$bus的自定义事件:
在绑定了$bus自定义事件(调用了$bus.$on())的组件实例中,最好在beforeDestroy钩子中,将当前组件实例使用到的自定义事件从$bus上解绑。
1beforeDestroy() {
2 this.$bus.$off([event1, event2, ...])
3},
自定义事件实现组件间数据通信案例
使用自定义事件实现一个todo-list案例,这个案例演示了如何实现组件间数据通信。
注:全局事件总线中,每条线的
$bus.$on()应该在早于所有的$bus.emit()时执行。
main.js
1import Vue from 'vue'
2import App from './App.vue'
3
4Vue.config.productionTip = false
5
6new Vue({
7 render: h => h(App),
8 beforeCreate() {
9 Vue.prototype.$bus = this // 安装全局事件总线
10 },
11}).$mount('#app')
todo-list-itme.vue
1<template>
2<li>
3 <label>
4 <input type="checkbox" :checked="isCompleted" @change="handleCheck"/>
5 <span>{{name}}</span>
6 </label>
7 <button class="btn btn-danger" @click="handleDelete">删除</button>
8</li>
9</template>
10
11<script>
12export default {
13 name: 'todo-list-item',
14 props: {
15 id: {
16 type: String,
17 required: true,
18 },
19 name: {
20 type: String,
21 required: true,
22 },
23 isCompleted: {
24 type: Boolean,
25 default: false,
26 },
27 },
28 methods: {
29 // 勾选或取消勾选
30 handleCheck() {
31 // 通知 App.vue 将对应的 todo 对象的 isCompleted 取反
32 this.$bus.$emit('check-todo', this.id)
33 },
34 // 删除
35 handleDelete() {
36 if (confirm(`是否确定删除${this.name}?`)) {
37 this.$bus.$emit('remove-todo', this.id)
38 }
39 },
40 }
41}
42</script>
43
44<style scoped>
45li {
46 list-style: none;
47 height: 36px;
48 line-height: 36px;
49 padding: 0 5px;
50 border-bottom: 1px solid #ddd;
51}
52
53li label {
54 float: left;
55 cursor: pointer;
56}
57
58li label li input {
59 vertical-align: middle;
60 margin-right: 6px;
61 position: relative;
62 top: -1px;
63}
64
65li button {
66 float: right;
67 display: none;
68 margin-top: 3px;
69}
70
71li:before {
72 content: initial;
73}
74
75li:last-child {
76 border-bottom: none;
77}
78
79li:hover {
80 background-color: #ddd;
81}
82
83li:hover button {
84 display: block;
85}
86</style>
todo-main.vue
1<template>
2<ul class="todo-main">
3 <!-- 将 checkTodo 传递给子组件 -->
4 <todo-list-item
5 v-for="todo in todos"
6 :key="todo.id"
7
8 :id="todo.id"
9 :name="todo.name"
10 :isCompleted="todo.isCompleted"
11 />
12</ul>
13</template>
14
15<script>
16import TodoListItem from './todo-list-item.vue'
17
18export default {
19 name: 'todo-main',
20 components: {
21 TodoListItem,
22 },
23 props: {
24 // 从父组件获取一个 todos 列表
25 todos: {
26 type: Array,
27 required: true,
28 },
29 },
30}
31</script>
32
33<style scoped>
34.todo-main {
35 margin-left: 0px;
36 border: 1px solid #ddd;
37 border-radius: 2px;
38 padding: 0px;
39}
40
41.todo-empty {
42 height: 40px;
43 line-height: 40px;
44 border: 1px solid #ddd;
45 border-radius: 2px;
46 padding-left: 5px;
47 margin-top: 10px;
48}
49</style>
todo-header.vue
1<template>
2<div class="todo-header">
3 <!-- 输入回车键添加 Todo -->
4 <input
5 type="text"
6 placeholder="请输入你的任务名称,按回车键确认"
7 @keyup.enter="add"
8 />
9</div>
10</template>
11
12<script>
13import {nanoid} from 'nanoid'
14
15export default {
16 name: 'todo-header',
17 data() {
18 return {
19 todoName: '',
20 }
21 },
22 methods: {
23 add(e) {
24 const elem = e.target
25
26 // 校验数据
27 if (!elem.value.trim()) {
28 return alert('输入不能为空!')
29 }
30
31 // 将用户输入包装为 todo 对象
32 const todo ={
33 id: nanoid(),
34 name: elem.value,
35 isCompleted: false,
36 }
37 // 通知 App 组件添加一个 todo
38 this.$emit('add-todo', todo)
39 // 清空输入
40 elem.value = ''
41 },
42 },
43}
44</script>
45
46<style scoped>
47.todo-header input {
48 width: 560px;
49 height: 28px;
50 font-size: 14px;
51 border: 1px solid #ccc;
52 border-radius: 4px;
53 padding: 4px 7px;
54}
55
56.todo-header input:focus {
57 outline: none;
58 border-color: rgba(82, 168, 236, 0.8);
59 box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
60}
61</style>
todo-footer.vue
1<template>
2<div class="todo-footer" v-show="total > 0">
3 <label>
4 <input type="checkbox" v-model="isCheckedAll"/>
5 </label>
6 <span>
7 <span>已完成{{completedTotal}}</span> / 全部{{total}}
8 </span>
9 <button class="btn btn-danger" @click="clearAllCompleted">清除已完成任务</button>
10</div>
11</template>
12
13<script>
14export default {
15 name: 'todo-footer',
16 props: {
17 /* todos: {
18 type: Array,
19 required: true,
20 }, */
21 // todo 总数
22 total: {
23 type: Number,
24 required: true,
25 },
26 // 被选 todo 的总数
27 completedTotal: {
28 type: Number,
29 required: true,
30 },
31 },
32 computed: {
33 // 计算是否全选或取消全选
34 isCheckedAll: {
35 get() {
36 return this.completedTotal === this.total && this.total > 0
37 },
38 set(isChecked) {
39 this.$emit('check-todos', isChecked)
40 }
41 }
42 },
43 methods: {
44 clearAllCompleted() {
45 if (this.completedTotal <= 0) {
46 alert('没有已完成的任务')
47 } else if (confirm('是否清除所有已完成的任务?')) {
48 this.$emit('clear-completed-todos')
49 }
50 },
51 },
52}
53</script>
54
55<style scoped>
56.todo-footer {
57 height: 40px;
58 line-height: 40px;
59 padding-left: 6px;
60 margin-top: 5px;
61}
62
63.todo-footer label {
64 display: inline-block;
65 margin-right: 20px;
66 cursor: pointer;
67}
68
69.todo-footer label input {
70 position: relative;
71 top: -1px;
72 vertical-align: middle;
73 margin-right: 5px;
74}
75
76.todo-footer button {
77 float: right;
78 margin-top: 5px;
79}
80</style>
App.vue
1<template>
2<div id="root">
3 <div class="todo-container">
4 <div class="todo-wrap">
5 <!-- 将 addTodo 函数传递给子组件 -->
6 <todo-header @add-todo="addTodo"/>
7 <!-- 将 todos 列表和 checkTodo 函数传递给子组件 -->
8 <todo-main
9 :todos="todos"
10 />
11 <!-- 将 todos 列表和 checkAllTodo 函数传递给子组件 -->
12 <todo-footer
13 :total="total"
14 :completedTotal="completedTotal"
15
16 @check-todos="checkAllTodo"
17 @clear-completed-todos="clearAllCompletedTodos"
18 />
19 </div>
20 </div>
21</div>
22</template>
23
24<script>
25import TodoHeader from './components/todo-header.vue'
26import TodoFooter from './components/todo-footer.vue'
27import TodoMain from './components/todo-main.vue'
28
29export default {
30 name: 'App',
31 components: {
32 TodoHeader,
33 TodoFooter,
34 TodoMain,
35 },
36 data() {
37 return {
38 // 将 todos 列表定义在 App.vue 中
39 // || 的原理是,符号左边的值结果不为真则返回符号右边的值
40 todos: JSON.parse(localStorage.getItem('todos')) || [],
41 }
42 },
43 watch: {
44 todos: {
45 deep: true,
46 handler(value) {
47 localStorage.setItem('todos', JSON.stringify(value))
48 },
49 },
50 },
51 computed: {
52 // 计算被选 todo 的总数
53 completedTotal() {
54 return this.todos.reduce(
55 (pre, todo) => pre + (todo.isCompleted ? 1 : 0), 0)
56 },
57 // 计算 todos 总数
58 total() {
59 return this.todos.length
60 },
61 },
62 methods: {
63 // 添加一个 todo
64 addTodo(todo) {
65 this.todos.unshift(todo)
66 },
67 // 勾选或取消一个 todo
68 checkTodo(id) {
69 this.todos.forEach(todo => {
70 if (todo.id === id) {
71 todo.isCompleted = !todo.isCompleted
72 }
73 })
74 },
75 // 删除一个 todo
76 deleteTodo(id) {
77 this.todos = this.todos.filter(todo => todo.id !== id)
78 },
79 // 选择所有或取消选择所有
80 checkAllTodo(checked) {
81 this.todos.forEach(todo => todo.isCompleted = checked)
82 },
83 // 清除所有已完成的 todo
84 clearAllCompletedTodos() {
85 this.todos = this.todos.filter(todo => !todo.isCompleted)
86 },
87 },
88 mounted() {
89 this.$bus.$on('check-todo', this.checkTodo)
90 this.$bus.$on('remove-todo', this.deleteTodo)
91 },
92 beforeDestroy() {
93 this.$bus.$off('check-todo')
94 this.$bus.$off('remove-todo')
95 },
96}
97</script>
98
99<style>
100body {
101 background: #fff;
102}
103
104.btn {
105 display: inline-block;
106 padding: 4px 12px;
107 margin-bottom: 0;
108 font-size: 14px;
109 line-height: 20px;
110 text-align: center;
111 vertical-align: middle;
112 cursor: pointer;
113 box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
114 border-radius: 4px;
115}
116
117.btn-danger {
118 color: #fff;
119 background-color: #da4f49;
120 border: 1px solid #bd362f;
121}
122
123.btn-danger:hover {
124 color: #fff;
125 background-color: #bd362f;
126}
127
128.btn:focus {
129 outline: none;
130}
131
132.todo-container {
133 width: 600px;
134 margin: 0 auto;
135}
136.todo-container .todo-wrap {
137 padding: 10px;
138 border: 1px solid #ddd;
139 border-radius: 5px;
140}
141</style>
评论