vue中$emit的使用

Vue中关于$emit的用法


一、背景

最近正官方文档学习vue框架,只掌握一门语言及其技术是不够的,需要不断充实自己,这样才会有更加宽阔的视野。


二、$emit的使用

$emit(event,arg):子组件可以回调自身或者父组件上的事件,参数event表示事件名,arg表示需要传递给回调事件的参数。

下面是官网给出的一段代码,我将对代码进行分析:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

<div id="todo-list-example">
<form v-on:submit.prevent="addNewTodo">
<label for="new-todo">Add a todo</label>
<input
v-model="newTodoText"
id="new-todo"
placeholder="E.g. Feed the cat"
>
<button>Add</button>
</form>
<ul>
<!--指明某个组件-->
<li
is="todo-item" // 指明了所使用的特定的组件
v-for="(todo, index) in todos" // for循环
v-bind:key="todo.id" // 标识组件唯一性,方便重用
v-bind:title="todo.title"
v-on:remove="todos.splice(index, 1)" // 删除元素
></li>
</ul>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 创建名为todo-item的组件
Vue.component('todo-item', {
template: '\
<li>\
{{ title }}\
<button v-on:click="$emit(\'remove\')">Remove</button>\
</li>\
',
props: ['title']
})

new Vue({
el: '#todo-list-example',
data: {
newTodoText: '',
todos: [
{
id: 1,
title: 'Do the dishes',
},
{
id: 2,
title: 'Take out the trash',
},
{
id: 3,
title: 'Mow the lawn'
}
],
nextTodoId: 4
},
methods: {
addNewTodo: function () {
this.todos.push({
id: this.nextTodoId++,
title: this.newTodoText
})
this.newTodoText = ''
}
}
});


说明:

1.li标签中使用is属性指明了所要使用的组件,其效果等价于直接写<todo-item>...</tode-item>,不过官网指说明了使用is可以避免不同浏览器的解析问题。

2.在模板中使用<button v-on:click="$emit(\'remove\')">Remove</button>\了模板,这里面使用到了$emit()方法,其在此代码中调用父组件中的remove属性,也就是todos.splice(index, 1)方法,删除数组中指定index和数量的项目。

3.<form v-on:submit.prevent="addNewTodo">这句代码中的sumbit.prevent相当于js中preventDefault方法,该方法通知浏览器不要执行该dom默认绑定的事件,在form中也就是取消页面跳转。

学无止境,要让自己的才华配的上自己的野心!