setup()方法
在組件創建之前執行,是組合式 API 的入口
方法可以接受兩個引數 props 和 context
setup方法中,要將資料暴露給頁面模板,需要結合ref,和reactive,并使用return
官網例子:
<!-- MyBook.vue -->
<template>
<div>{{ readersNumber }} {{ book.title }}</div>
</template>
<script>
import { ref, reactive } from 'vue'
export default {
setup() {
const readersNumber = ref(0)
const book = reactive({ title: 'Vue 3 Guide' })
// 暴露給模板
return {
readersNumber,
book
}
}
}
</script>
setup中的生命周期,使用時需要匯入
官網例子:
import { onMounted, onUpdated, onUnmounted } from 'vue'
export default {
setup() {
onMounted(() => {
console.log('mounted!')
})
onUpdated(() => {
console.log('updated!')
})
onUnmounted(() => {
console.log('unmounted!')
})
}
}
其中 beforeCreate 和 created 直接寫在setup中,官網沒有例子
setup() {
function fun () {
console.log("執行!");
}
fun();//"執行!"
}
}
setup標簽
使用時要注意vue3版本,好像是3.2開始支持
基本用法,直接在script標簽上增加setup
<script setup>
console.log('hello script setup')
</script>
資料在頁面模板上使用無需 return
<script setup>
import { ref } from 'vue';
// 變數
const msg = ref('Hello!');//回應式資料依然需要ref
// 函式
function log() {
console.log(msg);
}
</script>
<template>
<div @click="log">{{ msg }}</div>
</template>
關于組件
引入后直接使用,不需要花里胡哨
官網還有更多關于組件花里胡哨的用法,詳見使用組件
<script setup>
import MyComponent from './MyComponent.vue'
</script>
<template>
<MyComponent />
</template>
頂層await
官網解釋:
<script setup> 中可以使用頂層 await,結果代碼會被編譯成async setup()
<script setup>
const post = await fetch(`/api/post/1`).then(r => r.json())
</script>
就是在上面使用了await,setup就會變成 async setup()
最后

意思就是,script標簽上的 setup 不能和 script標簽上的src一起使用(沒人會這么干吧應該)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/300491.html
標籤:其他
