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
}
}