下面,我们来系统的梳理关于 Vue 3 <script setup> 语法糖 的基本知识点:


一、<script setup> 核心概念

1.1 什么是 <script setup>

<script setup> 是 Vue 3 中 Composition API 的编译时语法糖,它通过简化组件声明方式,显著减少样板代码,提供更符合直觉的开发体验。

1.2 设计目标与优势

目标实现方式优势
减少样板代码自动暴露顶层绑定代码更简洁
提升开发体验更自然的响应式写法开发更高效
更好的类型支持原生 TypeScript 集成类型安全
编译时优化编译阶段处理运行时更高效
逻辑组织组合式 API 原生支持关注点分离

1.3 与传统语法对比

<!-- 选项式 API -->
<script>
export default {props: ['message'],data() {return { count: 0 }},methods: {increment() {this.count++}}
}
</script><!-- Composition API 标准 -->
<script>
import { ref } from 'vue'export default {props: ['message'],setup(props) {const count = ref(0)function increment() {count.value++}return { count, increment }}
}
</script><!-- <script setup> 语法糖 -->
<script setup>
import { ref } from 'vue'const props = defineProps(['message'])
const count = ref(0)function increment() {count.value++
}
</script>

二、核心语法与特性

2.1 基本结构

<script setup>
// 所有顶层绑定都自动暴露给模板
import { ref } from 'vue'// 响应式状态
const count = ref(0)// 函数
function increment() {count.value++
}// 表达式
const double = computed(() => count.value * 2)
</script><template><button @click="increment">{{ count }} ({{ double }})</button>
</template>

2.2 编译器转换原理

输入:

<script setup>
const msg = 'Hello!'
</script>

输出:

<script>
export default {setup() {const msg = 'Hello!'return { msg } // 自动暴露所有顶层绑定}
}
</script>

2.3 自动暴露规则

  • 所有 import 导入
  • 顶层变量声明 (const, let, var)
  • 顶层函数声明
  • 顶层 classinterface (TypeScript)

三、组件与指令使用

3.1 组件使用

<script setup>
// 1. 导入组件
import MyComponent from './MyComponent.vue'// 2. 自动注册,无需components选项
</script><template><!-- 3. 直接在模板中使用 --><MyComponent />
</template>

3.2 动态组件

<script setup>
import { shallowRef } from 'vue'
import Home from './Home.vue'
import About from './About.vue'const currentComponent = shallowRef(Home)
</script><template><component :is="currentComponent" />
</template>

3.3 自定义指令

<script setup>
// 命名规范:vNameOfDirective
const vFocus = {mounted: el => el.focus()
}
</script><template><input v-focus />
</template>

四、Props与Emit处理

4.1 声明Props

<script setup>
// 选项式声明
const props = defineProps({title: String,count: {type: Number,required: true}
})// TypeScript接口声明
interface Props {title?: stringcount: number
}const props = defineProps<Props>()
</script>

4.2 声明Emit事件

<script setup>
// 数组形式
const emit = defineEmits(['update', 'delete'])// 对象形式(带验证)
const emit = defineEmits({update: (payload: { id: number }) => {return !!payload.id // 返回布尔值表示验证结果}
})// TypeScript类型声明
const emit = defineEmits<{(e: 'update', payload: { id: number }): void(e: 'delete', id: number): void
}>()

4.3 使用示例

<script setup>
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])function handleInput(e) {emit('update:modelValue', e.target.value)
}
</script><template><input :value="modelValue"@input="handleInput"/>
</template>

五、响应式与生命周期

5.1 响应式状态管理

<script setup>
import { ref, reactive, computed } from 'vue'// 基本类型
const count = ref(0)// 对象类型
const state = reactive({items: [],loading: false
})// 计算属性
const total = computed(() => state.items.length)// 侦听器
watch(count, (newVal, oldVal) => {console.log(`Count changed: ${oldVal} → ${newVal}`)
})
</script>

5.2 生命周期钩子

<script setup>
import { onMounted, onUnmounted } from 'vue'onMounted(() => {console.log('Component mounted')fetchData()
})onUnmounted(() => {console.log('Component unmounted')cleanup()
})
</script>

六、高级特性与模式

6.1 顶层await

<script setup>
const user = ref(null)
const posts = ref([])// 直接使用await - 自动编译为async setup()
const userData = await fetchUser()
user.value = userData// 结合watchEffect
watchEffect(async () => {if (user.value) {posts.value = await fetchPosts(user.value.id)}
})
</script>

6.2 使用插槽与上下文

<script setup>
import { useSlots, useAttrs } from 'vue'const slots = useSlots()
const attrs = useAttrs()// 访问默认插槽内容
const defaultSlotContent = slots.default?.()
</script>

6.3 暴露组件实例

<script setup>
import { ref } from 'vue'const inputRef = ref(null)// 暴露公共方法
function focusInput() {inputRef.value.focus()
}// 显式暴露
defineExpose({focusInput
})
</script><template><input ref="inputRef">
</template>

七、TypeScript集成

7.1 类型安全Props

<script setup lang="ts">
interface Props {title: stringcount?: numberitems?: string[]
}const props = defineProps<Props>()
</script>

7.2 泛型组件

<script setup lang="ts" generic="T">
import { ref } from 'vue'const items = ref<T[]>([])
const selected = ref<T>()function addItem(item: T) {items.value.push(item)
}
</script>

7.3 类型标注Ref

<script setup lang="ts">
import { ref } from 'vue'interface User {id: numbername: string
}// 显式类型标注
const user = ref<User | null>(null)// 初始化时推断
const count = ref(0) // Ref<number>
</script>

八、最佳实践与组织模式

8.1 代码组织建议

<script setup>
// ----------------------------
// 1. 导入部分
// ----------------------------
import { ref, onMounted } from 'vue'
import MyComponent from './MyComponent.vue'// ----------------------------
// 2. 定义Props/Emits
// ----------------------------
const props = defineProps({ /* ... */ })
const emit = defineEmits({ /* ... */ })// ----------------------------
// 3. 响应式状态
// ----------------------------
const count = ref(0)
const state = reactive({ /* ... */ })// ----------------------------
// 4. 计算属性和侦听器
// ----------------------------
const double = computed(() => count.value * 2)
watch(count, (val) => { /* ... */ })// ----------------------------
// 5. 函数声明
// ----------------------------
function increment() { count.value++ }// ----------------------------
// 6. 生命周期钩子
// ----------------------------
onMounted(() => { /* ... */ })// ----------------------------
// 7. 暴露API
// ----------------------------
defineExpose({ increment })
</script>

8.2 逻辑复用模式

<script setup>
// 使用自定义Hook
import { useCounter } from '@/composables/useCounter'const { count, increment } = useCounter(10)
</script>

8.3 性能优化

<script setup>
// 1. 使用shallowRef减少大型对象的响应式开销
const bigData = shallowRef(largeDataset)// 2. 使用markRaw避免不必要的响应式转换
const staticConfig = markRaw({ /* 大型配置对象 */ })// 3. 合理使用computed缓存计算结果
const filteredList = computed(() => bigData.value.filter(item => item.active)
)
</script>

九、常见问题与解决方案

9.1 响应式丢失问题

问题:解构Props导致响应式丢失

<script setup>
const { title } = defineProps(['title']) // 失去响应性
</script>

解决方案

<script setup>
const props = defineProps(['title'])
// 使用toRefs解构
const { title } = toRefs(props)
</script>

9.2 命名冲突问题

问题:导入组件与局部变量同名

<script setup>
import Button from './Button.vue'
const Button = ref(null) // 命名冲突
</script>

解决方案

<script setup>
import Button as BaseButton from './Button.vue'
const Button = ref(null) // 避免冲突
</script>

9.3 访问上下文问题

问题:无法直接访问 this

<script setup>
// 错误:this未定义
const router = this.$router
</script>

解决方案

<script setup>
import { useRouter } from 'vue-router'const router = useRouter() // 使用Composition API
</script>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/news/912045.shtml
繁体地址,请注明出处:http://hk.pswp.cn/news/912045.shtml
英文地址,请注明出处:http://en.pswp.cn/news/912045.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

MYSQL-InnoDB逻辑存储结构 详解

InnoDB逻辑存储结构 段—区—页—行 表空间&#xff1a; 默认情况下InnoDB有一个共享表空间ibdata1&#xff0c;所有数据放入这个表空间&#xff0c;如果开启了innodb_file_per_table&#xff08;默认ON&#xff09;&#xff0c;每张表都可以放到一个单独的表空间&#xff0…

[特殊字符] Python 批量合并 Word 表格中重复单元格教程(收货记录案例实战)

在日常办公中&#xff0c;Word 表格中常出现重复的“供应商名称”或“物料编码”&#xff0c;会导致表格冗余且视觉混乱。这时候&#xff0c;用 Python 自动合并重复单元格可以大幅提升表格专业度和可读性。本篇给大家演示如何用 python-docx 实现该功能。 ✅ 功能概览 自动读取…

从零构建Node.js服务托管前端项目

下面是一个完整的指南&#xff0c;教你如何从零开始构建一个Node.js服务来托管前端项目&#xff0c;并代理API请求到其他服务器。 1. 项目初始化 # 创建项目目录 mkdir node-proxy-server cd node-proxy-server# 初始化npm项目 npm init -y# 安装必要依赖 npm install expres…

Lynx vs React Native vs Flutter 全面对比:三大跨端框架实测分析

一文看懂三大热门跨端技术的历史渊源、架构机制、开发体验、包体积对比与性能评估。 我陪你用实测数据带你理性选型&#xff0c;不踩坑&#xff0c;不盲信。 1. 框架简介&#xff1a;它们是谁&#xff1f;来自哪里&#xff1f;干嘛用&#xff1f; 框架名称所属公司发布时间初衷…

CKESC的ROCK 180A-H 无人机电调:100V 高压冗余设计与安全保护解析

一、核心技术参数与性能指标 电压范围&#xff1a;支持 12~26S 锂电&#xff08;适配 110V 高压系统&#xff09;电流特性&#xff1a; 持续工作电流&#xff1a;90A&#xff08;特定散热条件&#xff09;瞬时耐流&#xff08;1 秒&#xff09;&#xff1a;220A&#xff0c;3 …

优化 ArcPy 脚本性能

使用并行处理 如果硬件条件允许&#xff0c;可以使用 Python 的并行处理模块&#xff08;如 multiprocessing&#xff09;来同时处理多个小任务。这样可以充分利用多核处理器的优势&#xff0c;提高脚本的执行效率。 import multiprocessing def process_raster(raster):arcpy…

Windows下CMake通过鸿蒙SDK交叉编译三方库

前言 华为鸿蒙官方的文章CMake构建工程配置HarmonyOS编译工具链 中介绍了在Linux平台下如何使用CMake来配置鸿蒙的交叉编译环境&#xff0c;编译输出在Harmony中使用的第三方so库以及测试demo。 本文主要是在Windows下实现同样的操作。由于平台差异的原因&#xff0c;有些细节…

从C学C++(6)——构造函数和析构函数

从C学C(6)——构造函数和析构函数 若无特殊说明&#xff0c;本博客所执行的C标准均为C11. 构造函数与析构函数 构造函数定义 构造函数是特殊的成员函数&#xff0c;当创建类类型的新对象&#xff0c;系统自动会调用构造函数构造函数是为了保证对象的每个数据成员都被正确初…

清理 Windows C 盘该注意什么

C 盘空间不足会严重影响系统性能。 清理 C 盘文件时&#xff0c;首要原则是安全。错误地删除系统文件会导致 Windows 无法启动。下面我将按照 从最安全、最推荐到需要谨慎操作的顺序&#xff0c;为你详细列出可以清理的文件和文件夹&#xff0c;并提供操作方法。 第一梯队&…

Python Selenium 滚动到特定元素

文章目录 Python Selenium 滚动到特定元素⚙️ **1. 使用 scrollIntoView() 方法&#xff08;最推荐&#xff09;**&#x1f5b1;️ **2. 结合 ActionChains 移动鼠标&#xff08;模拟用户行为&#xff09;**&#x1f9e9; **3. 使用坐标计算滚动&#xff08;精确控制像素&…

你写的 Express 接口 404,可能是被“动态路由”吃掉了

本文首发在我的个人博客&#xff1a;你写的 Express 接口 404&#xff0c;可能是被“动态路由”吃掉了 前情提要 最近参与公司的一个项目前端 React&#xff0c;后端用的 Express。目前我就做一些功能的新增或者修改。 对于 Express &#xff0c;本人没有公司项目实战经验&…

【Java面试】你是怎么控制缓存的更新?

&#x1f504; 一、数据实时同步失效&#xff08;强一致性&#xff09; 原理&#xff1a;数据库变更后立即失效或更新缓存&#xff0c;保证数据强一致。 实现方式&#xff1a; Cache Aside&#xff08;旁路缓存&#xff09;&#xff1a; 读流程&#xff1a;读缓存 → 未命中则…

react-嵌套路由 二级路由

什么是嵌套路由&#xff1f; 在一级路由中又内嵌了其他路由&#xff0c;这种关系就叫做嵌套路由&#xff0c;嵌套至一级路由内的路由又称作二级路由 嵌套路由配置 实现步骤 配置二级路由 children嵌套 import Login from "../page/Login/index"; import Home from …

【CMake基础入门教程】第八课:构建并导出可复用的 CMake 库(支持 find_package() 查找)

很好&#xff01;我们进入 第八课&#xff1a;构建并导出可复用的 CMake 库&#xff08;支持 find_package() 查找&#xff09;。 &#x1f3af; 本课目标 你将掌握&#xff1a; 如何构建一个库并通过 install() 导出其配置&#xff1b; 如何让别人在项目中使用 find_package…

Jenkins与Kubernetes深度整合实践

采用的非jenkins-slave方式 jenkins配置&#xff1a; Jenkins添加k8s master节点的服务器信息 在Jenkins容器内部与k8s master节点设置免费登录 # docker过滤查询出运行的Jenkins服务 $ docker ps | grep jenkins# 进入Jenkins容器内部 $ docker exec -it jenkins-server /bi…

GraphQL API-1

简介 判断GraphQL方式 判断一个网站是否使用了GraphQL API&#xff0c;可以通过以下几种方法&#xff1a; 1. 检查网络请求 查看请求端点 GraphQL 通常使用单一端点&#xff0c;常见路径如&#xff1a; /graphql/api/graphql/gql/query 观察请求特征 POST 请求为主&…

推荐C++题目练习网站

LeetCode LeetCode是一个全球知名的编程练习平台&#xff0c;提供大量C题目&#xff0c;涵盖数据结构、算法、系统设计等。题目难度从简单到困难&#xff0c;适合不同水平的学习者。平台支持在线编写代码并即时运行测试&#xff0c;提供详细的题目讨论区和官方解答。 Codeforc…

Spring Cloud 微服务(服务注册与发现原理深度解析)

&#x1f4cc; 摘要 在微服务架构中&#xff0c;服务注册与发现是整个系统运行的基础核心模块。它决定了服务如何被定位、调用和管理。 本文将深入讲解 Spring Cloud 中 Eureka 的服务注册与发现机制&#xff0c;从底层原理到源码分析&#xff0c;再到实际开发中的最佳实践&a…

【Linux 设备模型框架 kobject 和 kset】

Linux 设备模型框架 kobject 和 kset 一、Linux 设备模型概述二、kobject 与 kset 的核心概念1. kobject2. kset3. 关键数据结构 三、kobject 与 kset 的实现源码四、源码解析与使用说明1. kset 的创建与初始化2. kobject 的创建与属性3. sysfs 属性操作4. 用户空间访问示例 五…

一起学前端之HTML------(1)HTML 介绍

HTML 介绍 HTML 即超文本标记语言&#xff08;HyperText Markup Language&#xff09;&#xff0c;它是构成网页的基础技术之一。HTML 借助各种标签&#xff08;Tag&#xff09;对网页的结构与内容加以描述。下面为你介绍其核心要点&#xff1a; 关键特性 标签结构&#xff…