vue3 <script setup> 目前只是实验性用法,但是基本功能都有,包括props,emit,context,目前在一个项目中遇到一个问题就是:
子组件使用 <script setup>,在父组件无法获取子组件的方法或变量,除非子组件改成setup()方法,直到在stackoverflow看到有解决方法:
//子组件
<script setup>
import { useContext } from 'vue'
const showDialog = async id => {
let res = await getList({ id: id })
}
// expose
useContext().expose({ showDialog })
</script>
useContext().expose()可以把子组件的变量或方法暴露出去
这样就可以在父组件调用
//父组件
<template>
<Child ref="childRef" />
</template>
<script setup>
import Child from '@/components/Child.vue'
const childRef = ref(null)//子组件ref
function onShow(id) {
childRef.value.showDialog(id)//改变值或调用方法
}
</script>