vue中父组件调用子组件的方法

需求:vue中父组件调用子组件的方法

直接上代码

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
子组件:
<template>
<div>
{{num}}
</div>
</template>

<script>
export default {
data(){
return {
num:'123'
}
},
computed: {
},
components: {
'children': children
},
methods:{
childMethod() {
alert('childMethod do...')
}
},
created(){
}
}
</script>
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
父组件: 在子组件中加上ref即可通过this.$refs.ref.method调用
<template>
<div @click="parentMethod">
<children ref="c1"></children>
</div>
</template>

<script>
import children from 'components/children/children.vue'
export default {
data(){
return {
}
},
computed: {
},
components: {
'children': children
},
methods:{
parentMethod() {
console.log(this.$refs.c1) //返回的是一个vue对象,所以可以直接调用其方法
this.$refs.c1.childMethod();
}
},
created(){
}
}
</script>