Vue3 子组件向父组件传值的方法
有两种方式可以实现。
方式一:父组件传送一个处理方法给子组件,子组件调用这个处理方法把父组件关心的值作为参数传给这个处理方法。
例子: ================子组件 (父组件在下面)
# 当button被按下时,子组件里的request变量内容就会传给父组件的处理方法
>Generate Req
>
import { ref } from 'vue'
import { subRequest } from '@cp/MyTypes'
const request = ref
# 定义从父组件接收的处理方法
defineProps({
parentMethod: {
type: Function,
default: () => {},
},
})
================父组件
# 父组件传送给子组件的处理方法
import { ref } from 'vue'
import { subRequest } from '@cp/MyTypes'
const subRequests = ref
const childValueHandlingMethod = (request: subRequest) => {
console.log('Hello I am from children component', request)
# 父组件把子组件传过来的值放在了自己内部变量数组里
subRequests.value.push(request)
}
方式二:子组件发送emit方法给父组件
例子 在子组件里,就两步要做:1. 定义emits事件,2,在想要的时机发送emits事件 ================子组件 (父组件在下面)
{{ selectedValue
}}
v-for="theType in items" :key="`${theType}`" @click="click(theType)" >{{ theType }}
>
import { computed, defineEmits, ref } from 'vue'
import { ToRef } from 'vue-demi'
interface Props {
items: String[]
title: String
}
const props = defineProps
# 定义要发送的emit事件
const emit = defineEmits(['dropDownValueChange'])
const selectedValue = ref(props.title)
const click = (theType: string) => {
console.log('clicked', theType)
selectedValue.value = theType
# 发送事件,theType就是发送出去的值
emit('dropDownValueChange', theType)
}
================父组件
title="Fruits" :items="items" @dropDownValueChange="fruitValueChange" /> import { ToRef } from "vue-demi" const items = ['Apple', 'Orange', 'Pineapple', 'Banana'] const fruitValueChange = (e: any): void => { console.log('in parent compoennt, e=', e) } 这两种方法我都在自己代码里用过了,亲测可用。优不优雅就另说了,先能用再说吧 好文链接
发表评论