1.defineProps 用来接收父组件传来的 props
2.defineEmits 子组件向父组件事件传递
3.defineExpose 组件暴露出自己的属性,在父组件中可以拿到值或函数,父组件用ref接收即可
<template>
<div class="about">
<h1 @click="ziupdata" >绑定值msg:{{ msg }}</h1>
</div>
</template>
<script lang="ts" setup>
//因为这里用了script的setup方式就用不到 defineComponent 这个定义组件的api了
import { useSlots, useAttrs, defineProps, onMounted, watchEffect, defineComponent,defineEmits } from 'vue';
// 跳路由用
import router from '@/router/index';
// 获取路由参数
import { useRoute } from 'vue-router';
const route = useRoute();
const slots = useSlots();
const attrs = useAttrs();
//获取子组件传的值
const props = defineProps({
idq: String,
});
//暴露出去的变量
defineExpose({
saveFn:()=>{do...}, //可以返回函数
ziname
})
//自定义函数,父组件可以触发
const em=defineEmits(['updata'])
const ziupdata=()=>{
em("updata",'我是子组件的值')
}
const msg = 1234;
onMounted(() => {
console.log('onMounted:', 123444);
});
//watchEffect 会最先执行 自动收集里面的依赖更新调用
watchEffect(() => {
console.log('watchEffect:', 3333);
});
//console.log(slots, attrs);
//console.log('props', props);
//console.log('route:', route.query);
</script>
// 如果用到ts 来接收 props 里面有两种写法,这是第一种,它可以自行推断接收的值是什么类型(对象除外)
const props = defineProps({
page: { // 页码
type: Number,
default: 1
},
limit: { // 每页大小
type: number,
default: 10
},
loadList: { // 列表加载函数
type: Function,
default: () => {}
},
obj: { // 假如传过来一个对象
type: Object as PropType<{ a: string, b: number }>,
required: true // 必填项
}
})
// 第二种写法,纯ts写法
interface PropsType {
page: number,
limit: number,
loadList: () => void
}
// 如果不需要写默认值的话,可以直接
const props = defineProps<PropsType>()
// 如果需要写默认值,只能调用提供的编译函数
const props = withDefaults(defineProps<PropsType>(), {
page: 1,
limit: 10,
loadList: () => {}
})
// 但是自我感觉,还是第一种方法更为简介明了,具体选择哪种就是看个人喜好了
TS结合vue3的一些初级使用方法 - 知乎