使用script setup语法糖优化你的vue3代码

本文介绍了Vue 3中引入的scriptsetup语法糖,如何通过它简化组件代码,提升可读性和维护性。通过实例展示了如何导入组件、定义props和暴露变量,以及scriptsetup的最新用法和VSCode插件的配合使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意:本文章写于setup语法糖早期提出阶段,如今部分用法已经更改,最新的用法请以官方最新提案为主。

请移步官方文档     https://v3.vuejs.org/api/sfc-script-setup.htmlicon-default.png?t=LA92https://v3.vuejs.org/api/sfc-script-setup.html

script setup是vue3中新引入的语法糖,目的是简化使用Composition API时冗长的模板代码。

例如:

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { MyButton } from '@/components'

export default defineComponent({
  components: {
    MyButton
  },
  props: {
      name: String
  },
  setup() {
    const count = ref(0)
    const inc = () => count.value++

    return {
      count,
      inc,
    }
  },
})
<script>

可见,当我们需要引入一个components时,不仅需要在文件头部显式import进行导入,而且需要components字段加入声明。不仅如此,在setup中声明的变量如果需要被模板使用,那么需要在setup的尾部显式return返回,如果你的组件模板使用的变量不多,那么这种情况还可以勉强接受。但是当你的变量和方法逐渐增加时,每次都要在setup后进行return返回,这无疑是一件枯燥的事情,在重构代码时,你也会面临巨大挑战。

为了解决这个问题,vue3添加了script setup语法糖提案。

像上面这段代码,使用script setup语法糖重构后,将变成:

<script setup lang="ts">
import { defineComponent, ref, defineProps } from 'vue'
import { MyButton } from '@/components'

defineProps<{
    name:string
}>()

const count = ref(0)
const inc = () => count.value++

<script>

怎么样,代码是不是变得可读性更强,更优雅了。

接下来我们看一下具体的用法。

基本用法

若要使用script setup语法,只需在原vue文件中的script标签加入setup属性。

<script setup lang="ts">

<script>

使用后意味着,script标签内的内容相当于原本组件声明中setup()的函数体,不过也有一定的区别。

使用setup中的参数

<script setup="props, context" lang="ts">

<script>

像这样,只要在setup处声明即可自动导入,同时也支持解构语法:

<script setup="props, { emit }" lang="ts">

<script>

暴露变量到模板

曾经的提案中,如果需要暴露变量到模板,需要在变量前加入export声明:

export const count = ref(0)

不过在新版的提案中,无需export声明,编译器会自动寻找模板中使用的变量,只需像下面这样简单的声明,即可在模板中使用该变量

const count = ref(0)

导入component或directive

直接import即可,无需额外声明

import { MyButton } from "@/components"
import { directive as clickOutside } from 'v-click-outside'

与原先一样,模板中也支持使用kabab-case来创建组件,如<my-button />

定义props,emit

<script setup>
  import { defineProps, defineEmit, useContext } from 'vue'

  const props = defineProps({
    foo: String,
  })
  const emit = defineEmit(['change', 'delete'])
</script>

增强的props类型定义:

const props = defineProps<{
  foo: string
  bar?: number
}>()

const emit = defineEmit<(e: 'update' | 'delete', id: number) => void>()

不过注意,采用这种方法将无法使用props默认值。

获取 slots 和 attrs

<script setup lang="ts">
  import { useContext } from 'vue'

  const { slots, attrs } = useContext()
</script>

await语法支持

在script setup内可以直接使用await语法:

<script setup>
  const post = await fetch(`/api/post/1`).then((r) => r.json())
</script>

定义组件其他字段

在script setup内使用export default,其内容会被处理后放入原组件声明字段。

<script setup>
  export default {
    name: "MyComponent"
  }
</script>

vscode配套插件使用

volar是一个vscode插件,用来增强vue编写体验,使用volar插件可以获得script setup语法的最佳支持。

### 使用 Vue 3 Setup 语法糖 Vue 3 的 `setup` 函数提供了一种更简洁的方式来编写组合式 API 逻辑。通过使用 `<script setup>` 语法糖,可以进一步简化模板中的代码结构并提高可读性。 #### 基本用法 当使用 `<script setup>` 时,所有的声明都会自动暴露给模板和其他选项,无需显式返回对象: ```html <template> <div>{{ message }}</div> </template> <script setup> import { ref } from &#39;vue&#39; const message = ref(&#39;Hello World&#39;) </script> ``` 这种方式使得组件更加直观易懂[^1]。 #### 处理 Props 和 Emit 对于处理属性 (`props`) 和事件发射 (`emit`),可以直接解构它们而不需要像传统方式那样定义 `setup` 函数参数: ```html <template> <button @click="increment">Count is: {{ count }}</button> </template> <script setup> import { defineProps, defineEmits, ref } from &#39;vue&#39; // 解构 props const { count } = defineProps([&#39;count&#39;]) // 定义 emit 并调用 const emit = defineEmits([&#39;update&#39;]) function increment() { emit(&#39;update&#39;, count + 1) } </script> ``` 这不仅减少了样板代码的数量,还提高了开发效率[^2]。 #### 组件间的通信 为了实现父子组件之间的数据共享或者状态管理,在子组件内部可以通过 `provide/inject` 来完成依赖注入操作: ```html <!-- Parent Component --> <template> <child-component /> </template> <script setup> import ChildComponent from &#39;./ChildComponent.vue&#39; import { provide, reactive } from &#39;vue&#39; const state = reactive({ user: &#39;John Doe&#39;, }) provide(&#39;state&#39;, state) // 提供全局变量 </script> <!-- Child Component --> <template> <p>User Name: {{ state.user }}</p> </template> <script setup> import { inject } from &#39;vue&#39; const state = inject(&#39;state&#39;) // 注入父级提供的变量 </script> ``` 这种模式非常适合构建大型应用,因为它允许开发者轻松地管理和传递复杂的状态树.
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值