Option APIの書き方
import Vue from "vue"
export default Vue.extend({
})
↓
<script lang="ts">
import { defineComponent } from "@vue/composition-api"
export default defineComponent({
setup() {
const { data: posts } = await useFetch('/api/posts')
}
})
</script>
↓ setup() の糖衣構文が <script setup> になります。次のように記述できます
( <script setup> の中では(現在まだ実験的な機能である Suspense と組み合わせて使用することで)トップレベルの await を使うことができます。その結果、コードは async setup() としてコンパイルされます。
https://bit.ly/3APAi9U
<script setup lang="ts">
const { data: posts } = await useFetch('/api/posts')
</script>
引用 : https://zenn.dev/coedo/articles/86bc31acb4ea47
また script setup はライフサイクルでいうところの、beforeCreate と created のライフサイクルで実行されます
https://v3.ja.vuejs.org/guide/composition-api-lifecycle-hooks.html
data → ref, reactive
dataはComposition APIでrefあるいはreactiveで表現される。
refはプリミティブな値を管理し、reactiveはオブジェクトや配列を管理する。
そのため、reactiveの方が今までの使い方に近い。
ただし、refにオブジェクトや配列を渡すと、内部でreactiveが呼ばれるため問題なく使える。
https://nansystem.com/nuxt-composition-api-v2-diff/
特に使い分けるベストプラクティスがあるわけではなさそう(どちらでもご自由に。)
● ref
・プリミティブ、オブジェクト両方で使用できる
・refで定義したリアクティブな変数の値にアクセスするには.valueを使用する必要がある
// ref の定義
const mydata = ref("スタッフ")
// ref の参照
console.log( mydata.value );
// ref の参照(テンプレート内では自動的に内部の値に浅くアンラップ(ref でラップされた値を取り出す)されます)
<template>
<div>
<span>{{ mydata }}</span>
</div>
</template>
// ref の更新
mydata.value = '社長'
● reactive
・プリミティブ値は受け取れない
・リアクティビティの消失に注意(refも同じだと思われるが。。。要検証)
https://kobatech-blog.com/vue-composition-api-ref-reactive/
https://vuejs.org/guide/typescript/composition-api.html#typing-component-props
<script setup lang="ts">
type Props = {
testName: string;
};
// props を受け取る(デフォルト値なし)
const props = defineProps<Props>();
// props を受け取る(デフォルト値あり)
const props = withDefaults(defineProps<Props>(), {
testName: "hogehoge",
});
</script>