一、通过ref调用子组件的方法
父组件可以通过ref属性来获取子组件实例,从而调用子组件的方法。
1.在子组件中设置ref属性
<template>
<div>
<button @click="show">显示</button>
</div>
</template>
<script>
export default {
name: 'child',
methods: {
show() {
console.log('子组件方法被调用!');
}
}
}
</script>
2.在父组件中使用ref获取子组件实例
<template>
<div>
<child ref="child"></child>
<button @click="handleClickChildComponent">调用子组件方法</button>
</div>
</template>
<script>
export default {
name: 'parent',
methods: {
handleClickChildComponent() {
this.$refs.child.show();
}
}
}
</script>
上述代码中,父组件通过"ref"属性获取子组件实例,并通过"$refs.child"来调用子组件的"show"方法。
二、通过$children调用子组件的方法
父组件可以通过"$children"属性来获取所有子组件的实例,从而调用子组件的方法。
1.在子组件中暴露出需要调用的方法
<template>
<div>
<p>子组件</p>
</div>
</template>
<script>
export default {
name: 'child',
methods: {
show() {
console.log('子组件方法被调用');
}
}
}
</script>
2.在父组件中通过"$children"属性调用子组件方法
<template>
<div>
<child v-for="(child, index) in $children" :key="index"></child>
<button @click="handleClickChildComponent">调用子组件方法</button>
</div>
</template>
<script>
export default {
name: 'parent',
methods: {
handleClickChildComponent() {
this.$children.forEach(child => {
child.show();
})
}
}
}
</script>
上述代码中,父组件通过"$children"属性获取所有子组件实例,并遍历调用所有子组件的"show"方法。
三、通过改变从父组件传入的值调用子组件的方法
当从父组件传入的 prop 值发生变化时,子组件会重新渲染。从而调用子组件的方法。
1.在子组件中定义方法并在钩子函数中调用
<template>
<div>
<p>子组件</p>
</div>
</template>
<script>
export default {
name: 'child',
props: ['isUpdate']
methods: {
show() {
console.log('子组件方法被调用');
}
},
create() {
this.show();
}
}
</script>
2.改变从父组件传入的值,重新渲染子组件
<template>
<div>
<child :isUpdate="isUpdate"></child>
<button @click="handleClickChildComponent">调用子组件方法</button>
</div>
</template>
<script>
export default {
name: 'parent',
data(){
return {
isUpdate: false
}
},
methods: {
handleClickChildComponent() {
this.isUpdate = true;
}
}
}
</script>
上述代码中,父组件通过改变传入的子组件的值,导致子组件重新渲染,钩子函数调用"show"方法。