1. 父組件中獲取子組件方法javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<template>
<div>
<v-header></v-header>
<v-content></v-content>
<v-footer></v-footer>
</div>
</template>
<script>
import
vHeader from
'./Header'
;
import
vContent from
'./Content'
;
import
vFooter from
'./Footer'
;
export
default
{
components:{vHeader,vContent,vFooter},
created(){
console.log(
this
.$children)
//輸出結果[VueComponent,VueComponent,VueComponent],此時能夠經過下標獲取響應組件,如獲取vHeader爲this.$children[0].
}
}
</script>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<template>
<div>
<v-header ref=
'header'
></v-header>
<v-content ref=
'content'
></v-content>
<v-footer ref=
'footer'
></v-footer>
</div>
</template>
<script>
import
vHeader from
'./Header'
;
import
vContent from
'./Content'
;
import
vFooter from
'./Footer'
;
export
default
{
components:{vHeader,vContent,vFooter},
created(){
console.log(
this
.$refs);
//輸出結果:{header:VueComponent,content:VueComponent,footer:VueComponent},此時能夠經過對象key進行獲取響應組件,如vHeader組件獲取爲this.$refs.header
}
}
</script>
|
2. 子組件中定義父組件所要觸發事件vue
1
2
3
4
5
6
7
8
9
10
|
<script>
export
default
{
methods:{
childAction(val=
'hello world'
){
console.log(val)
}
//此時在父組件,能夠經過獲取相應子組件,使用對象key值childAction對其進行調用,當前函數形參非必須
}
}
</script>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<script>
export
default
{
mounted(){
this
.$on(
'bridge'
,(val)=>{
this
.childAction(val);
});
///此時經過$on進行監聽中間橋接函數bridge對目的方法childAction進行觸發
},
methods:{
childAction(val=
'hello world'
){
console.log(val)
}
}
}
</script>
|
3. 父組件調用子組件方法java
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
44
45
46
|
<template>
<div>
<v-header ref=
'header'
></v-header>
<v-content ref=
'content'
></v-content>
<v-footer ref=
'footer'
></v-footer>
<button @click=
'emitChild1'
>ref與on觸發</button>
<button @click=
'emitChild2'
>ref直接觸發</button>
<button @click=
'emitChild3'
>children與on觸發</button>
<button @click=
'emitChild4'
>children直接觸發</button>
</div>
</template>
<script>
import
vHeader from
'./Header'
;
import
vContent from
'./Content'
;
import
vFooter from
'./Footer'
;
export
default
{
components:{vHeader,vContent,vFooter},
methods:{
emitChild1(){
this
.$refs.footer.$emit(
'bridge'
,
'你好嗎!'
);
//打印: 你好嗎
this
.$refs.footer.$emit(
'bridge'
);
//打印:hello world
},
emitChild2(){
this
.$refs.footer.childAction(
'你好嗎!'
);
//打印: 你好嗎
this
.$refs.footer.childAction();
//打印:hello world
},
emitChild3(){
this
.$children[2].$emit(
'bridge'
,
'你好嗎!'
);
//打印: 你好嗎
this
.$children[2].$emit(
'bridge'
);
//打印:hello world
},
emitChild4(){
this
.$children[2].childAction(
'你好嗎!'
);
//打印: 你好嗎
this
.$children[2].childAction();
//打印:hello world
},
}
}
</script>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<template>
<footer>This is footer-component</footer>
</template>
<script>
export
default
{
mounted(){
this
.$on(
'bridge'
,(val)=>{
this
.childAction(val);
});
},
methods:{
childAction(val=
'hello world'
){
console.log(val)
}
}
}
</script>
|