3、使用script setup語法糖優化你的vue3代碼


一、准備

1.1 簡介

setup語法糖 一個減少重復代碼的語法糖,之前setup語法糖的提案在修改階段,現階段已經定稿,詳情看下面的語法

1.2 插件准備

如果你使用vscode編輯器,最好安裝 Volar 插件,它和 Vetur 一樣也會對.Vue格式的文件高亮顯示,支持vue2、vue3,並且還多了在 template 中對 TypeScript 的支持,自定義組件標簽高亮,以及本文要說的 setup語法糖 支持
注意來自Volar插件的提示:

Note: You need to disable Vetur to avoid conflicts.

Vetur 也是之前寫 vue2 很常用的插件,但是它已經十分落后,不支持 vue3 的 setup 語法糖,會發生沖突,如果你想寫 vue3 的 setup 語法糖請卸載或者禁用它,安裝 Volar 足矣。

<script setup lang="ts">
import HelloWorld from "./components/HelloWorld.vue";  //此處使用 Vetur 插件會報紅
</script>

 

二、語法

2.1 組件引入

之前的寫法

<script lang="ts">
import { defineComponent } from 'vue';
import HelloWord from '@/components/HelloWord.vue';
export default defineComponent({
  name: 'Home',
  components:{
    HelloWord
  }
});
</script>

 

現在的寫法

<script setup lang="ts">
import HelloWord from '@/components/HelloWord.vue'; //不用注冊,引入即注冊
</script>

 

2.2 定義組件的 props

<script setup lang="ts">
import { ref,defineProps } from 'vue'
type Props={
  msg:string
}
defineProps<Props>();
</script>

 

2.3 定義響應變量、函數、監聽、計算屬性....

<script setup lang="ts">
import { ref,computed,watchEffect } from 'vue'
const count = ref(0); //不用 return ,直接在 templete 中使用
const addCount=()=>{  //定義函數,使用同上
  count.value++;
}
const howCount=computed(()=>"現在count值為:"+count.value);//定義計算屬性,使用同上
watchEffect(()=>console.log(count.value)); //定義監聽,使用同上
//...some code else
</script>

 

2.3 使用 await 異步

注意在vue3的源代碼中,setup執行完畢,函數 getCurrentInstance 內部的有個值會釋放對 currentInstance 的引用,await 語句會導致后續代碼進入異步執行的情況。所以上述例子中最后一個 getCurrentInstance() 會返回 null,建議使用變量保存第一個 getCurrentInstance() 返回的引用.

三、其他

3.1 語法糖實現

vue文件代碼

<template>
  <div>{{ msg }}</div>
</template>
<script setup>
  const msg = 'Hello!'
</script>

 

編譯后的js代碼:

export default {
  setup() {
    const msg = 'Hello!'

    return function render() {
      // has access to everything inside setup() scope
      // 在函數 setup 作用域,函數 render 能訪問 setup 的一切,
      return h('div', msg)
    }
  }
}

 

注意到,即使普通變量也能作為模版被置入 template 中被編譯,某些人認為這不合適,不夠分離。我覺得還好,還ok

 

 

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語法的最佳支持。
————————————————
版權聲明:本文為CSDN博主「ooooonly_real」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_17794813/article/details/117381219


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM