vue3父组件使用ref调用子组件方法
•
前端
在vue2中,父组件通过ref调用子组件的方法只需要给子组件添加ref属性,然后使用this.$refs.XXX.method即可
export default {
mounted() {
this.$refs.myInput.focus();
}
}
但是在vue3中,子组件需先使用defineExpose将方法暴露给父组件
//子组件
const myMethod = () => {
console.log('Hello from myMethod!');
};
// 将 myMethod 暴露给父组件
defineExpose({ myMethod });
//父组件中调用
调用方法如下:
1、使用getCurrentInstance
import { getCurrentInstance, onMounted } from 'vue';
onMounted(() {
const instance = getCurrentInstance();
const myComponent = instance.refs.myComponentRef;
myComponent.myMethod();
})
2、使用ref函数创建一个响应式的引用,并将其绑定到子组件上
const MyComponentsRef = ref(null); MyComponentsRef.value.myMethod();
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/29c77ce359.html
