vue3 setup语法糖 父组件如何调用子组件方法?

// father
<template>
  <children ref="childRef"/>
</template>

<script setup>
import { onMounted } from "vue";
import children from "./children"
ref: childRef = null
onMounted(()=>{
  console.log(childRef);       //  output:  {}
})
</script>


//  children
<template>
  <div>div</div>
</template>

<script setup>
const demo = () => {
  console.log("demo");
}
</script>

如题,子组件应该如何导出方法呢?

一些牢骚, 我到github上提问(https://github.com/vuejs/rfcs...),也许是我姿势不对,他们直接给我关了……没看到啥引导说明啊

更新解决方案 2021-3-13

直接去 https://discord.com/channels/... 问的,经过一番充满智慧的讨论后终于找到了解决方案 ^v^
// children
<script setup name="可以在这里设定组件名,github上找到的,未验证">
import { useContext } from "vue"
const { expose } = useContext()

const refresh = () => {
  console.log("refresh");
}

expose({
  refresh
})
</script>
// father
<script setup>
import { onMounted } from "vue";
import children from "./children"
ref: childRef = null
onMounted(()=>{
  childRef.refresh();  // output: refresh
})
</script>

ps. 不保证以后也这么写

阅读 26.9k
5 个回答

文档里啥都有
https://v3.vuejs.org/guide/co...


Parent.vue

<template>
  <Child ref="childRef" />
</template>

<script setup>
import { onMounted, ref } from "vue";
export { default as Child } from "./Child";
onMounted(() => {
  childRef.value.demo()
});
export const childRef = ref(null);
// 如果用ref语法糖应该是像下面这样写,然后上面的ref不用import
// (ref语法糖的写法)用codesandbox没通过,不知道有没有实装,(没实装的话)可能得手动去拉github上的代码才能用
// ref: childRef = null
</script>
<style>
</style>

Child.vue

<template>
  <div>child</div>
</template>

<script setup>
export const demo = () => {
  console.log("demo");
}
</script>

子组件暴露方法和ref语法糖没啥关系,直接export就行了
https://github.com/vuejs/rfcs...
https://github.com/vuejs/rfcs...

使用 setup 语法糖,需要在子组件中使用 defineExpose 将父组件需要的属性和方法暴露出来后,父组件才能通过 childRef 来使用这些方法和属性。

ref是异步,直接console没东西,自己写个setTimeout或者用nextTick试试

新手上路,请多包涵

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题