特点
- 代码更少、更简洁的,不需要使用 return {} 暴露变量和方法了,使用组件时不需要主动注册
- 更好的 TypeScript 支持,使用纯 TypeScript 声明 props 和抛出事件,更加简洁直观
缺点则是需要多学一些API
示例
以下是一个简单的示例
<template>
<h1>{
{
msg }}</h1>
<h1>{
{
logout() }}</h1>
<button type="button" @click="add">count is: {
{
count }}</button>
<ComponentA />
</template>
<script lang="ts" setup>
import {
ref } from 'vue'
// 外部引入的方法,不需要通过 methods 选项来暴露它,模板可以直接使用
import {
logout } from '../../utils/http'
// 外部引入的组件,不需要通过 components 选项来暴露它,模板可以直接使用
import ComponentA from './tree/index.vue'
//接收prpos
defineProps<{
msg: String,
}>()
// 变量声明,模板可以直接使用
const count = ref(0)
// 函数声明,模板可以直接使用
function add() {
count.value++
}
</script>
参考文献:链接地址