轉自:http://www.jb51.net/article/115624.htm
vue1.0中 vm.$dispatch 和 vm.$broadcast 被棄用,改用$emit,$on
1
|
vm.$on(
event, callback )
|
監聽當前實例上的自定義事件。事件可以由vm.$emit觸發。回調函數會接收所有傳入事件觸發函數的額外參數。
1
|
vm.$emit(
event, […args] )
|
觸發當前實例上的事件。附加參數都會傳給監聽器回調。
例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<template>
<ratingselect
@select-type= "onSelectType" ></ratingselect>
</template>
<script>
data
() {
return {
selectType:
0,
},
methods:
{
onSelectType
(type) {
this .selectType
= type
}
}
</script>
|
父組件使用@select-type="onSelectType"@就是v-on的簡寫,監聽由子組件vm.$emit觸發的事件,通過onSelectType()接受從子組件傳遞過來的數據,通知父組件數據改變了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<template>
<div>
<span
@click= "select(0,
$event)"
:class= "{'active':
selectType===0}" ></span>
<span
@click= "select(1,
$event)"
:class= "{'active':
selectType===1}" ></span>
<span
@click= "select(2,
$event)"
:class= "{'active':
selectType===2}" ></span>
</div>
</template>
<script>
data
() {
return {
selectType:
0,
},
methods:
{
select
(type, event) {
this .selectType
= type
this .$emit( 'select-type' ,
type)
}
}
</script>
|
子組件通過$emit來觸發事件,將參數傳遞出去。
以上所述是小編給大家介紹的vue2.0 中#$emit,$on的使用詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對腳本之家網站的支持!
原文鏈接:http://blog.csdn.net/m0_37068028/article/details/72898119
如對本文有疑問,請提交到交流社區,廣大熱心網友會爲你解答!! 點擊進入社區