vue3 ts子组件传参到父组件
时间: 2023-12-12 21:04:32 浏览: 31
子组件传参到父组件可以通过自定义事件和$emit方法实现。具体步骤如下:
1.在子组件中定义一个方法,用于触发自定义事件并传递参数。
```vue
<template>
<div class="child">
子组件
<button @click="handleClick">传递参数到父组件</button>
</div>
</template>
<script setup lang="ts">
import { defineEmits } from 'vue'
defineEmits(['sendData'])
const handleClick = () => {
const data = '这是子组件传递给父组件的数据'
// 触发自定义事件,并将数据作为参数传递给父组件
emit('sendData', data)
}
</script>
```
2.在父组件中通过ref获取子组件实例,并在mounted钩子函数中监听子组件的自定义事件。
```vue
<template>
<div class="parent">
父组件
<Child ref="child" @sendData="handleReceiveData"></Child>
<div>接收到的数据:{{ receivedData }}</div>
</div>
</template>
<script setup lang="ts">
import Child from './Child.vue'
import { ref, reactive } from 'vue'
const child = ref(null)
const state = reactive({
receivedData: ''
})
const handleReceiveData = (data: string) => {
// 接收子组件传递过来的数据
state.receivedData = data
}
// 在mounted钩子函数中获取子组件实例
const mounted = () => {
child.value = ref.value
}
</script>
```
3.在父组件中定义一个方法,用于接收子组件传递过来的数据。
```vue
<script setup lang="ts">
import Child from './Child.vue'
import { ref, reactive } from 'vue'
const child = ref(null)
const state = reactive({
receivedData: ''
})
const handleReceiveData = (data: string) => {
// 接收子组件传递过来的数据
state.receivedData = data
}
// 在mounted钩子函数中获取子组件实例
const mounted = () => {
child.value = ref.value
}
</script>
```