vue3通过defineExpose传值
时间: 2023-11-04 12:57:18 浏览: 140
使用defineExpose`可以在Vue 3中将值从子组件传递给父组件。在子组件中,你可以使用`defineExpose`将需要传递给父组件的值暴露出去。在父组件中,你可以使用`ref`来获取子组件的实例,并访问子组件暴露的值。
下面是一个示例代码:
子组件:
```vue
<template>
<div>{{ date }}</div>
</template>
<script lang="ts" setup>
import { ref, defineEmits, defineExpose } from 'vue'
const date = ref()
const emit = defineEmits(['change'])
const onConfirm = () => {
emit('change', date)
}
emit('change', date)
defineExpose({ onConfirm, date })
</script>
<style lang="scss" scoped></style>
```
父组件:
```vue
<template>
<div>
<Child ref="child"></Child>
</div>
</template>
<script setup>
import { ref } from 'vue'
import Child from './child.vue'
const child = ref(null)
setTimeout(() => {
console.log(child.value.date)
}, 1000)
</script>
```
在这个例子中,子组件通过`defineExpose`将`onConfirm`方法和`date`值暴露出去,父组件通过`ref`获取子组件的实例,并在1秒后访问子组件的`date`值。
阅读全文
相关推荐
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)