// 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. 不保证以后也这么写
###文档里啥都有
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...
ref是异步,直接console没东西,自己写个setTimeout或者用nextTick试试