Vue3 script-setup 清新單文件寫法

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

直到我發(fā)現(xiàn)了如下的 script-setup 寫法,讓我覺得這才應(yīng)該是真正的 vue3

如何定義組件名 => name

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

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

<template>
  <Foo />
</template>

如何導(dǎo)入指令 => directive

導(dǎo)入指令的用法同 導(dǎo)入組件

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

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

如何使用 props

通過defineProps指定當(dāng)前props類型的同時(shí),獲得上下文的props對(duì)象
在script中需要props[key]引用,而template中可直接調(diào)用key

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

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

如何使用 emit

通過defineEmit指定當(dāng)前組件含有的觸發(fā)事件
事件通過 defineEmit 返回的上下文 emit 進(jìn)行觸發(fā)

<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 函數(shù)的規(guī)則,僅在組件加載時(shí)調(diào)用一次
<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>

獲取數(shù)據(jù)

基本上就是在之前的方法名前加上了一個(gè) on,且并沒有提供 onCreated 的鉤子,因?yàn)樵?setup() 內(nèi)執(zhí)行就相當(dāng)于在 created 階段執(zhí)行。下面我們?cè)?mounted 階段來請(qǐng)求數(shù)據(jù):

import { reactive, onMounted } from 'vue'

export default {
  setup() {
    const state = reactive({
      hits: []
    })
    onMounted(async () => {
      const data = await fetch(
        'https://hn.algolia.com/api/v1/search?query=vue'
      ).then(rsp => rsp.json())
      state.hits = data.hits
    })
    return state
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Vue3剛出來的時(shí)候,我覺得 vue-hooks 時(shí)代來了,終于可以拋棄單文件組件的寫法,徹底融入到函數(shù)式編程中,...
    Ankh閱讀 42,735評(píng)論 16 21
  • 可能很多同學(xué)(包括我)剛上手 Vue 3.0 之后,都會(huì)覺得開發(fā)過程似乎變得更繁瑣了,Vue 官方團(tuán)隊(duì)當(dāng)然不會(huì)無視...
    硅谷干貨閱讀 34,000評(píng)論 0 22
  • 前期準(zhǔn)備 1.使用vue-cli創(chuàng)建一個(gè) vue3 + TS 的項(xiàng)目 2.vscode禁用Vetur,下載Vola...
    無言_f70a閱讀 1,076評(píng)論 0 0
  • 一、Vue3啟程 1. 初始Vue3 姓名:{{name}} 年齡:{{age}} 修改數(shù)據(jù) /...
    野鴿兒閱讀 741評(píng)論 0 0
  • vue3支持三種寫法 Option Api (與vue2寫法相同) Composition API (setup(...
    lowpoint閱讀 9,081評(píng)論 1 16

友情鏈接更多精彩內(nèi)容