Vue3 script-setup 超清新單文件寫法

Vue3剛出來的時候,我覺得 vue-hooks 時代來了,終于可以拋棄單文件組件的寫法,徹底融入到函數式編程中,在react和vue之間無縫切換,然而脫離了 模板 的vue,寫起來簡直太刻板了,所謂的compositionApi的作用感官上并沒有那么明顯。

直到我發現了如下的script-setup寫法,讓我覺得這才應該是真正的 vue3

如何定義組件名 => name

script-setup 無法指定當前組件的名字,所以使用的時候以文件名為主

如何導入組件 => components

在 script-setup 中導入任意的組件就可以直接在 template 中使用

<script setup>
  // imported components are also directly usable in template
  import Foo from './Foo.vue'
</script>

<template>
  <Foo />
</template>


如何導入指令 => directive

導入指令的用法同 導入組件

<script setup>
  import { directive as clickOutside } from 'v-click-outside'
</script>

<template>
  <div v-click-outside />
</template>


如何使用 props

通過defineProps指定當前props類型的同時,獲得上下文的props對象
在script中需要props[key]引用,而template中可直接調用key

<script setup>
  import { defineProps } from 'vue'

  // expects props options
  const props = defineProps({
    foo: String,
  })
</script>


如何使用 emit

通過defineEmit指定當前組件含有的觸發事件
事件通過 defineEmit 返回的上下文 emit 進行觸發

<script setup>
  import { defineEmits } from 'vue'

  // expects emits options
  const emit = defineEmits(['update', 'delete'])
</script>


如何獲取 slots 和 attrs

<script setup>
  import { useContext } from 'vue'

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


Note

<script setup></script> 遵循 setup 函數的規則,僅在組件加載時調用一次
<script setup>
  // Top level await can be used inside <script setup>. 
  // The resulting setup() function will be made async.
  const post = await fetch(`/api/post/1`).then((r) => r.json())
</script>

傳送門 => vue-script-setup官方資料

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容