script setup 是 vue3 的新语法糖,简化了以往的组合式 API 必须返回(return)的写法,并且有更好的运行时性能。内部的属性或方法可以直接使用,无需 return 返回;引入子组件可以自动注册,无需 components 注册
<template>
<SetUp ref="child"></SetUp>
</template>
<script setup>
import SetUp from "./SetUp.vue" //自动注册
import { toRefs,defineProps,useAttrs, useSlots,onMounted } from "vue"
let todoList = [
{todo:"看海",isCheck:false},
{todo:"浪漫",isCheck:true},
] //不需要 return 和 setup函数
接收 props 中的数据时,使用 defineProps 方法来获取
const props = defineProps({
a: String,
b: String
})
const { a, b } = toRefs( props )
useAttrs 方法 获取 attrs 属性
useSlots 方法获取 slots 插槽
defineEmits 方法获取 emit 自定义事件
const slots = useSlots();
const attrs = useAttrs();
const emits = defineEmits(['getChild']);
// defineExpose无需导入,直接使用
defineExpose({todoList });
//父组件引用
let child = ref(null);
onMounted(() => {
console.log(child.value.msg); // Child Components
})
</script>