ライブラリのインストール
npm i @nuxtjs/composition-api
公式の説明にそって設定を追加
nuxt.config.js
buildModules: [
// https://github.com/antfu/unplugin-vue2-script-setup
// To use TypeScript with Nuxt, install the @nuxtjs/typescript-module but disable the type check:
['@nuxt/typescript-build', { typeCheck: false }],
'@nuxtjs/composition-api/module',
'unplugin-vue2-script-setup/nuxt',
],
package.json
// And then use vue-tsc to do the type check at build time: "build": nuxt build", ↓ "build": "vue-tsc --noEmit && nuxt build",
tsconfig.json
"types": [ "@nuxt/types", "@nuxtjs/axios", "@types/node", "unplugin-vue2-script-setup/types" // 追加 ]
コンポーネント側で使う
import { defineComponent, ref } from '@nuxtjs/composition-api'
export default defineComponent({
name: 'IndexPage',
setup(){
const hoge = ref('a');
return {hoge}
}
vue-template-compiler のバージョンアップ
@nuxtjs/composition-api のバージョンを 0.33.1 に更新したら vue-template-compiler がひっかかったので更新
yarn add vue-template-compiler
"vue-template-compiler": "^2.7.14", // ← ^2.6.14
書き方Tips
useMeta
import { defineComponent, useMeta } from '@nuxtjs/composition-api'
export default defineComponent({
head{}, // 公式によるとこれ必要
setup(props){
const { title } = useMeta()
title.value = 'Application'+ mode.value;
}
})
watch
import { defineComponent, watch} from '@nuxtjs/composition-api'
export default defineComponent({
props: {
forChildVal: {
type: String,
default: () => {
return ''
},
},
},
setup(props){
watch(
() => props.forChildVal,
(current) => {
// 処理
}
)
return {}
}
})