问答

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

作者:admin 2021-04-21 我要评论

// fathertemplate children ref="childRef"//templatescript setupimport { onMounted } from "vue";import children from "./children"ref: childRef = nullon...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)
// 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试试

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • vue3 setup语法糖 父组件如何调用子组

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

  • NacosSync0.4.2 zk迁移到nacos

    NacosSync0.4.2 zk迁移到nacos

  • 新版untiy新建项目报错是什么问题?

    新版untiy新建项目报错是什么问题?

  • 静态html模板有什么组件化开发方案?

    静态html模板有什么组件化开发方案?

腾讯云代理商
海外云服务器