How to do annotating correctly in Vue2.x Class component with TypeScript

398 Views Asked by At

I've adopted my project with @vue/composition-api

// main.ts
import Vue from 'vue'
import VueCompositionApi from '@vue/composition-api'

Vue.use(VueCompositionApi)

But when setting setup() in a Class Component,

<template>
  <h1>{{ name }}</h1>
</template>

<script lang="ts">
import { ComputedRef, ref } from '@vue/composition-api'
import { Component, Vue } from 'vue-property-decorator'

function useName(): { name: ComputedRef<string> } {
  const name = ref('Joe')
  return { name }
}

@Component({
  setup() {
    const { name } = useName()
    return { name }
  }
})
export default class TestName extends Vue {}
</script>

I always get a warning message like: enter image description here

I know that comes from the missing property definition in regular data field in Class Component. But by using @vue/composition-api, we actually don't need to set the data property.

Is there anyone knows how to how to solving the issue.

1

There are 1 best solutions below

1
On BEST ANSWER

Your code works without error in a Vue project, but your screenshot of the browser console shows that you're using Nuxt.

To use the Composition API in Nuxt, install @nuxtjs/composition-api (which includes @vue/composition-api, so need to explicitly install it):

npm i -S @nuxtjs/composition-api

Then in nuxt.config.js, add it as a build module:

module.exports = {
  buildModules: [
    '@nuxtjs/composition-api/module'
  ],
}