defineProps 写法
父组件向子组件传递数据
msg: 这种为必填传参 父组件在引用子组件时 需传递对应参数 否则后台会提示告警
msg?:这种为可不传值的写法
引用类型需通过函数回调来设置默认值 基本类型可以直接赋值
const props = withDefaults(
defineProps<{
msg?:string,
ageList?:Array<number>
}>(), {
msg: "默认值",
ageList: ()=>[0,13,331]
})
defineEmits写法
子组件向父组件传递事件
子组件定义
e?:"parentClick1",data?:string
前面的问号表示 父组件没设置这个事件也是没关系的 不会提示告警
后面的问号表示 父组件没设置这个事件的参数也是没关系的 不会提示告警
<template>
<button @click="clickEmits1">子传父1</button>
<button @click="clickEmits2">子传父2</button>
</template>
<script setup lang="ts">
//只能有一个 defineEmits
//方式一
//const emits1 = defineEmits(["parentClick1","parentClick2"])
//方式二
const emits = defineEmits<{(e:"parentClick1",data:string):void,(e:"parentClick2",data:string):void}>()
const clickEmits1 = ()=>{
emits('parentClick1',"我是子组件1 clickEmits1")
}
const clickEmits2 = ()=>{
emits('parentClick2',"我是子组件2 clickEmits2")
}
</script>
父组件定义
<script setup lang="ts">
import DefineEmits from 'com/DefineEmits.vue';
const parentClick1= (args:string)=>{
alert(args)
}
const parentClick2= (args:string)=>{
alert(args)
}
</script>
<template>
<DefineEmits @parent-click1="parentClick1" @parent-click2="parentClick2" />
</template>
SlotsAttrs写法
在子组件中使用父组件的插槽 获取到插槽可插槽内的DOM元素
注意的是 import 就不能使用别名进行导入import SlotsAttrs from './components/SlotsAttrs.vue';
传递Atrrs 时提示的告警是因为我们传递的属性是没有解析的
<script setup lang="ts">
import SlotsAttrs from './components/SlotsAttrs.vue';
</script>
<template>
<SlotsAttrs a="1" b="2" msg="hello" class="child" style="color:red">
<template #header>
<h1>我是父组件插槽</h1>
</template>
</SlotsAttrs>
</template>
<template>
<h1>子组件引用slot</h1>
<slot name="header" />
</template>
<script setup lang="ts">
import { onMounted, useSlots ,useAttrs} from 'vue';
defineProps(
{msg:String}
)
onMounted(()=>{
console.log(solts.header && solts.header())
console.log(attrs)//要除了Props传递的参数 props里面的有的参数 这里将不会传递 会自动剔除
})
const attrs = useAttrs()
const solts = useSlots()
</script>
DefineExpose写法
<template>
<h1>{{msg}}</h1>
<h1>{{num}}</h1>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const msg = ref('child msg')
const num = ref(123);
const handle = ()=>{
console.log("暴露子组件")
}
defineExpose({
msg,num,handle
})
</script>
<script setup lang="ts">
import DefineExpose from 'com/DefineExpose.vue';
import { onMounted, ref } from 'vue';
let chlid = ref<{msg:String}|null>(null)
onMounted(() => {
console.log(chlid.value)
})
</script>
<template>
<DefineExpose ref="chlid"></DefineExpose>
</template>