Vue3中父子组件传参

471 阅读1分钟

子组件接收父组件传过来的参数

父组件(传参)
调用子组件child
<child :name="name" :arr="[1,2,3,4]"></child>
let name = "栗子"
子组件(接收参数)
//接收父组件传来的name值,使用defineProps
注意: 没有使用TS的话,defineProps就是一个函数
const props = defineProps({
    name: {
        type: String,
        default: "默认值"
    }
})
console.log(props.name)
使用TS的话,可以直接使用泛型字面量
const props = defineProps<{
    name: string
    arr: number[]
}>()

TS中特有定义默认值 withDefaults
withDefaults(defineProps<{
    name: string
    arr: number[]
}>(),{
    arr: () => [888]   //定义arr的默认值
})

子组件给父组件传值

子组件(传参)
<button @click="send">给父组件传值</button>

//给父组件传值使用defineEmits
//方式一
const emit = defineEmits(['my-click'])
const send = ()=>{
    emit('my-click',"要传的参数")
}
//方式二(使用了TS)
const emit = defineEmits<{
    (e: "my-click", list: string): void
}>()
父组件
<child @my-click="getList"></child>

const getList = (list: string)=>{
    console.log(list)
}

子组件给父组件暴露方法或属性(defineExpose)

子组件
//暴露的属性或方法
defineExpose({
    name: "栗子",
    open: ()=>console.log("open")
})
父组件
//需要使用ref获取组件的实例
<child ref="child"></child>

import child from './components/child.vue'
//注意:类型为TS自带的
const child = ref<InstanceType<typeof child>>()
//获取子组件暴露的属性
console.log(child.value.name)