Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use vue class component with composition api in Vue2 by typescript

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { CustomerContext, getCustomerRepository } from '@/composables/customerRepository'

@Component
export default class CustomerList extends Vue {
  search = ''

  setup(): CustomerContext {
    const ctx = getCustomerRepository()
    return ctx
  }
}
</script>

In Vue 2, I want to use the Composition API with the class component style by TypeScript, but I'm not sure I have the correct syntax. Also, the setup() function did not get invoked automatically.

Can vue-class-component work with the Compostion API in TypeScript?

like image 991
robertzml Avatar asked Nov 24 '20 08:11

robertzml


People also ask

Does vue2 support TypeScript?

TypeScript also improves developer ergonomics via type-based auto-completion in IDEs. Vue is written in TypeScript itself and provides first-class TypeScript support. All official Vue packages come with bundled type declarations that should work out-of-the-box.

Can we use composition API in Vue 2?

Browser Compatibility. @vue/composition-api supports all modern browsers and IE11+. For lower versions IE you should install WeakMap polyfill (for example from core-js package).

How do you define props in Vue composition API?

You define a prop named disabled in MyComponent. vue . ... and then add the component like this, passing in disabled . Note that :disabled="true" and just disabled mean the same thing in both cases - when props are defined or not.


1 Answers

Vue 2

First, make sure you've installed the @vue/composition-api plugin for Vue 2:

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

Vue.use(VueCompositionApi)

Then define setup() as a @Component option (not as a class method):

// MyComponent.vue
@Component({
  setup(props, context) {
    //...
  }
})
export default class CustomerList extends Vue {
  //...
}

Vue 3

For Vue 3, [email protected] exports a setup() API that you'd assign to a local variable:

<template>
  <div>counter: {{myContext.counter}}</div>
  <button @click="myContext.increment">Increment</button>
</template>

<script lang="ts">
import { Vue, setup } from 'vue-class-component'
import { ref } from 'vue'

export default class MyComponent extends Vue {
  myContext = setup(() => {
    const counter = ref(0)

    return {
      counter,
      increment() {
        counter.value++
      }
    }
  })
}
</script>

Note: As of [email protected], setup() receives no arguments, including the context and props arguments from the setup() used in the Options API.

like image 147
tony19 Avatar answered Oct 20 '22 02:10

tony19