You can use setup syntax sugar directly by adding the setup attribute in the script tag.
After using setup syntax sugar, there is no need to write a setup function; components only need to be introduced without registration; properties and methods do not need to be returned and can be used directly in the template .
<template> <my-component @click="func" :numb="numb"></my-component> </template> <script lang="ts" setup> import {ref} from 'vue'; import myComponent from '@/component/myComponent.vue'; //此时注册的变量或方法可以直接在template中使用而不需要导出 const numb = ref(0); let func = ()=>{ numb.value++; } </script>
defineProps: Child component receives props passed from parent component
defineEmits: The child component calls the method in the parent component
defineExpose: The child component exposes properties, which can be obtained in the parent component
Parent component code
<template> <my-component @click="func" :numb="numb"></my-component> </template> <script lang="ts" setup> import {ref} from 'vue'; import myComponent from '@/components/myComponent.vue'; const numb = ref(0); let func = ()=>{ numb.value++; } </script>
Child component code
<template> <div>{{numb}}</div> </template> <script lang="ts" setup> import {defineProps} from 'vue'; defineProps({ numb:{ type:Number, default:NaN } }) </script>
Subcomponent code
<template> <div>{{numb}}</div> <button @click="onClickButton">数值加1</button> </template> <script lang="ts" setup> import {defineProps,defineEmits} from 'vue'; defineProps({ numb:{ type:Number, default:NaN } }) const emit = defineEmits(['addNumb']); const onClickButton = ()=>{ //emit(父组件中的自定义方法,参数一,参数二,...) emit("addNumb"); } </script>
Parent component code
<template> <my-component @addNumb="func" :numb="numb"></my-component> </template> <script lang="ts" setup> import {ref} from 'vue'; import myComponent from '@/components/myComponent.vue'; const numb = ref(0); let func = ()=>{ numb.value++; } </script>
Subcomponent code
<template> <div>子组件中的值{{numb}}</div> <button @click="onClickButton">数值加1</button> </template> <script lang="ts" setup> import {ref,defineExpose} from 'vue'; let numb = ref(0); function onClickButton(){ numb.value++; } //暴露出子组件中的属性 defineExpose({ numb }) </script>
Parent component code
<template> <my-comp ref="myComponent"></my-comp> <button @click="onClickButton">获取子组件中暴露的值</button> </template> <script lang="ts" setup> import {ref} from 'vue'; import myComp from '@/components/myComponent.vue'; //注册ref,获取组件 const myComponent = ref(); function onClickButton(){ //在组件的value属性中获取暴露的值 console.log(myComponent.value.numb) //0 } //注意:在生命周期中使用或事件中使用都可以获取到值, //但在setup中立即使用为undefined console.log(myComponent.value.numb) //undefined const init = ()=>{ console.log(myComponent.value.numb) //undefined } init() onMounted(()=>{ console.log(myComponent.value.numb) //0 }) </script>