父組件向子組件通信
業務場景:現在我要在父組件點擊一個回退按鈕,這個回退會傳進子組件中(子組件中有兩步進程),子組件來處理。
解決方案
起初我是父組件通過props傳值,但是發現只有組件第一次加載時才能傳值,通過事件改變的父組件值並不會再通過過props傳遞,也就是說props只有加載組件時才會工作,並不會根據值改變動態操作
后面,我是通過操作dom的方法,this.$refs.children這樣直接操作子組件
1
2
3
4
5
|
<ProgressTwo ref=
"progressTwo"
v-
else
-
if
=
"progress==2"
@second=
"recordProgress"
></ProgressTwo>
//這是子組件
goSecond:
function
(){
//這是操作子組件的方法
this
.$refs.progressTwo.second =
true
this
.second =
false
}
|
注釋:其實我們一直被父子組件概念束縛了,子組件就是相當於一個被包裹的div,只是那個div里有很多標簽而已,或者可以理解為我們在父組件里用iframe嵌套了一個頁面,這個頁面是子組件(這是幫助理解的粗話)
現在講講父子組件通信
父組件向子組件傳值
父組件
html
1
2
3
|
<div>
<NotFound v-
else
:searchThing=
"search"
></NotFound>
//search是父組件要傳的值
</div>
|
子組件
在script中拿值
1
2
3
|
props:{
searchThing: String
//也可以給它一個默認值 (defaultAddress: {Type: Object,default:()=> 'default'})
},
|
子組件向父組件傳值
通過發射函數
子組件
在script中通過函數告訴父組件
1
2
3
|
gotoPay:
function
(){
this
.$emit(
'second'
,data)
//data是你要向父組件傳的值(可傳可不傳看需求)
}
|
父組件
html
1
|
<ProgressTwo ref=
"progressTwo"
v-
else
-
if
=
"progress==2"
@second=
"recordProgress"
></ProgressTwo>
|
script
父組件通過自定義的second事件監聽子組件的發射
1
2
3
4
5
6
7
8
9
10
11
|
recordProgress:
function
(val){
//val用於接收子組件傳過來的值
if
(val==
true
){
this
.second = val
}
else
{
if
(val==
false
){
this
.progress = 3
}
else
{
this
.progress = 1
}
}
},
|