位置:- 正文

Vue3 <script setup lang=“ts“> 使用指南(vue3 script setup withdefault)

编辑:rootadmin
Vue3 <script setup lang=“ts“> 使用指南

推荐整理分享Vue3 <script setup lang=“ts“> 使用指南(vue3 script setup withdefault),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:vue3 script setup 绑定值,vue3 script setup 生命周期,vue3 script setup name,vue3 script setup reactive,vue3 script setup 绑定值,vue3 script setup props,vue3 script setup props,vue3 script setup props,内容如对您有帮助,希望把文章链接给更多的朋友!

本文主要是讲解 <script setup> 与 TypeScript 的基本使用。

<script setup> 是什么?

Vue3 <script setup lang=“ts“> 使用指南(vue3 script setup withdefault)

<script setup> 是在单文件组件 (SFC) 中使用 composition api 的编译时语法糖。

本文写作时,vue 使用的 3.2.26 版本。

1.1. 发展历程

我们先看看 vue3 <script setup> 的发展历程:

Vue3 在早期版本( 3.0.0-beta.21 之前)中对 composition api 的支持,只能在组件选项 setup 函数中使用。<template><h1>{{ msg }}</h1><button type="button" @click="add">count is: {{ count }}</button><ComponentA /><ComponentB /></template><script>import { defineComponent, ref } from 'vue'import ComponentA from '@/components/ComponentA'import ComponentB from '@/components/ComponentB'export default defineComponent({name: 'HelloWorld',components: { ComponentA, ComponentB },props: {msg: String,},setup(props, ctx) {const count = ref(0)function add() {count.value++}// 使用return {} 把变量、方法暴露给模板return {count,add,}},})</script>

在 3.0.0-beta.21 版本中增加了 <script setup> 的实验特性。如果你使用了,会提示你 <script setup> 还处在实验特性阶段。

在 3.2.0 版本中移除 <script setup> 的实验状态,从此,宣告 <script setup> 正式转正使用,成为框架稳定的特性之一。

<script setup lang="ts">import { ref } from 'vue'import ComponentA from '@/components/ComponentA'import ComponentB from '@/components/ComponentB'defineProps<{ msg: string }>()const count = ref(0)function add() {count.value++}</script>x<template><h1>{{ msg }}</h1><button type="button" @click="add">count is: {{ count }}</button><ComponentA /><ComponentB /></template>1.2. 优势

与组件选项 setup 函数对比, <script setup> 的优点:

更少、更简洁的代码,不需要使用 return {} 暴露变量和方法了,使用组件时不需要主动注册了;更好的 Typescript 支持,使用纯 Typescript 
本文链接地址:https://www.jiuchutong.com/zhishi/300015.html 转载请保留说明!
下一篇链接:https://www.jiuchutong.com/zhishi/300016.html
免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络