1.$refs的使用場景
父組件調用子組件的方法,可以傳遞數據。
父組件:
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
|
<div id=
"app"
>
<child-a ref=
"child"
></child-a>
<button @click=
"getMyEvent"
>點擊父組件</button>
<div>
<script>
import ChildA from
'./child.vue'
export
default
{
components:{
ChildA
},
data(){
return
{
msg:
'我是父組件的數據'
}
},
methods:{
getMyEvent(){
//調用子組件的方法,child是上邊ref起的名字,emitEvent是子組件的方法。
this .$refs.child.emitEvent( this .msg)
}
}
}
</script>
|
子組件:
1
2
3
4
5
6
7
8
9
10
11
12
|
<template>
<button>點擊我</button>
</template>
<script>
export
default
{
methods:{
emitEvent(msg){
console.log(
'接收的數據------'
+msg)
}
}
}
</script>
|
2.$emit的使用
子組件調用父組件的方法並傳遞數據。
子組件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<template>
<button @click=
"emitEvent"
>點擊我</button>
</template>
<script>
export
default
{
data(){
return
{
msg:
'我是子組件的數據'
}
},
methods:{
emitEvent(){
//通過按鈕的點擊事件觸發方法,然后用$emit觸發一個my-event的自定義方法,傳遞this.msg數據。
this
.$emit(
'my-event'
,
this
.msg)
}
}
}
</script>
|
父組件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<template>
<div id=
"app"
>
<child-a @my-event=
"getMyEvent"
></child-a>
//父組件通過監測my-event事件執行一個方法,然后取到子組件中傳遞過來的值。
</div>
</template>
<script>
import childA from
'./child.vue'
;
export
default
{
components:{
childA
},
methods:{
getMyEvent(msg){
console.log(
'接收數據---'
+msg);
//接收數據,我是子組件的數據
}
}
}
</script>
|
3.$on的使用場景
兄弟組件之間相互傳遞數據。
this.$root.$emit("change",'傳的值'); //可以從$root獲取vue的實例
首先創建一個Vue的空白實例(兄弟組件的橋梁)
1
2
|
import Vue from 'vue' ;
export default new Vue();
|
子組件A:發送放使用$emit自定義事件把數據帶過去。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<template>
<div>
<span>A組件-{{msg}}</span>
<input type=
"button"
value=
"把A組件數據傳遞給B"
@click=
"send"
>
</div>
</template>
<script>
import eventBus from
'./eventBus'
;
export
default
{
data(){
return
{
msg:{
a:
'111'
,
b:
'222'
}
}
},
methods:{
send(){
eventBus.$emit( 'aevent' , this .msg)
}
}
}
</script>
|
子組件B:接收方通過$on監聽自定義事件的callback接收數據
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<template>
<div>
<span>B組件,A傳的數據為--{{msg}}</span>
</div>
</template>
<script>
import eventBus from
'./eventBus.vue'
export
default
{
data(){
return
{
msg:
''
}
},
mounted(){
eventBus.$on( 'aevent' ,(val)=>{ //監聽事件aevent,回調函數要使用箭頭函數。
console.log(val); //打印結果;我是a組件的數據。
})
}
}
</script>
|
父組件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<template>
<div>
<childa></childa>
<br/>
<childb></childb>
</div>
</template>
<script>
import childa from
'./childa.vue'
;
import childb from
'./childb.vue'
;
export
default
{
componets:{
childa,
childb
},
data(){
return
{
msg:
''
}
}
}
</script>
|
4.$off的使用場景
vm.$off( [event, callback] )
參數:
{string | Array<string>} event (只在 2.2.2+ 支持數組)
{Function} [callback]
用法:
移除自定義事件監聽器。
如果沒有提供參數,則移除所有的事件監聽器;
如果只提供了事件,則移除該事件所有的監聽器;
如果同時提供了事件與回調,則只移除這個回調的監聽器。
eventBus.$off(
"aevent");