7
<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?

0

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Use class to write setup, and support vue2 and vue3

<template>
    <p>{{ count.text }}</p>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { Setup, Hook } from 'vue-class-setup';

@Setup
class Count {
    public value = 0;
    public get text() {
        return String(this.value);
    }
    @Hook('mounted')
    public init() {
        this.value++;
    }
}

export default defineComponent({
    setup() {
        return {
            count: new Count()
        }
    }
})
</script>

https://github.com/fmfe/vue-class-setup

Comments

0
import ClassComponent from 'vue-class-component'
ClassComponent.registerHooks(['setup'])

Put this at the beginning of your project, then every thing will work as you expected

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.