2024年4月5日发(作者:)

在 Vue3 中,子组件的方法可以通过父组件提供,然后子组件在需要时调用这些方法。可以通过以下步骤实

现:

1. 在父组件中,使用

provide

函数为子组件提供方法。例如:

javascript

import { provide, ref } from 'vue';

export default {

setup() {

const childMethods = ref(null);

provide('childMethods', childMethods);

function childMethod() {

('子组件的方法被调用');

}

return {

childMethod

};

}

}

2. 在子组件中,使用

inject

函数注入父组件提供的方法。例如:

javascript

import { inject, onMounted } from 'vue';

export default {

setup() {

const childMethods = inject('childMethods');

onMounted(() => {

ethod();

});

}

}

3. 可以在

router-view

中调用子组件的方法。例如:

在父组件中:

html

复制代码

复制代码

复制代码

在子组件中:

javascript

export default {

setup() {

// 其他代码...

复制代码

const routerView = getCurrentInstance().proxy.$elector('.vue-router-

view'); // 获取 router-view 实例

routerView.$emit('childMethod'); // 触发子组件方法

}

}