子组件接收父组件传过来的参数
父组件(传参)
调用子组件child
<child :name="name" :arr="[1,2,3,4]"></child>
let name = "栗子"
子组件(接收参数)
注意: 没有使用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]
})
子组件给父组件传值
子组件(传参)
<button @click="send">给父组件传值</button>
const emit = defineEmits(['my-click'])
const send = ()=>{
emit('my-click',"要传的参数")
}
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")
})
父组件
<child ref="child"></child>
import child from './components/child.vue'
const child = ref<InstanceType<typeof child>>()
console.log(child.value.name)