A guide on leveraging Vue class components alongside the composition API in Vue2 using 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>

Exploring the use of the Composition API in Vue 2 with TypeScript and class component style. Unsure if the syntax is correct and encountering issues where the setup() function is not automatically invoked.

Questioning if vue-class-component can be used effectively with the Composition API in TypeScript.

Answer №1

Vue 2

To start, ensure that you've added the @vue/composition-api plugin to your Vue 2 project:

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

Vue.use(VueCompositionApi)

Next, define the setup() function within a @Component option (instead of as a class method):

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

Vue 3

For Vue 3, the

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b0d0e1e5618171a08">[email protected]</a>
function provides a setup() API that should be assigned 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>

Please note: Starting from

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="205655450d434c41535352">[email protected]</a>
, the setup() function no longer receives any arguments, including the context and props parameters used in the Options API's setup().

Answer №2

Create a setup using classes to support both Vue 2 and Vue 3

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

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

export default defineComponent({
    setup() {
        return {
            counter: new Counter()
        }
    }
})
</script>

Check out the source on GitHub

Answer №3

const Component = require('vue-class-component')
Component.hooks(['initialize'])

Insert this code snippet at the start of your program, and all functionality will operate as intended.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The variable "vue" is not properly defined within the instance, yet it is being called

I'm currently working on a Vue app and encountering an issue. The onScroll function is working correctly, but when I click the button component to trigger the sayHello function, I receive an error message. The error states: "Property or method &apo ...

Is there a way to adjust the state value in Pinia within a Vue3 component test, and have an impact on the component?

When testing the component using pinia with vue-test-utils, I encountered difficulty in modifying the state value stored in pinia. Despite trying multiple methods, I was unable to achieve the desired result. The original component and store files are provi ...

What could be causing the QullJS delta to display in a nonsensical sequence?

The outcome showcased in the delta appears as: {"ops":[{"retain":710},{"insert":" yesterday, and she says—”\n“The clinic?","attributes":{"prediction":"prediction"}},{"del ...

Include quotation marks around a string in C# to convert it into JSON format

I am utilizing a service that operates with JSON format. However, the JSON data I am receiving does not include double quotes around keys and values. Here is an example of the data I have: [{name:{buyerfirstname:Randy, buyermiddlename:null, buyerlastnam ...

The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this: constructor(public http: HttpClient) { this.data = null; this.http.get(this.url).subscribe((datas: any) => { this.dbUrl = datas[0].db_url2; console.log(this ...

How can I access the parameter value for the tooltip callback function within echarts?

I am attempting to retrieve the value for this specific Apache EChart from within the callback function of the tooltip formatter. When I manually input the value, the formatting function operates correctly: formatter: (params:any) => `$ ${Math.round(pa ...

There is no such member found in the component declaration, template variable declarations, or element references

Seeking help for a simple fix. The objective is to have the element slide out from the top of the page upon hover. The code is functioning correctly, but I am encountering an error. Error: [Angular] Identifier 'compartmentOpen' is not defined. ...

Bundle multiple internal modules in typescript for easy exporting

Currently, I am exploring the idea of implementing TypeScript in node.js. I have been accustomed to using TypeScript with the ///<reference.../> syntax for internal modules. However, as projects grow larger, managing interlinking references between m ...

Tips for automatically resizing a canvas to fit the content within a scrollable container?

I have integrated PDF JS into my Vue3 project to overlay a <canvas id="draw_canvas"> on the rendered pdf document. This allows me to draw rectangles programmatically over the pdf, serving as markers for specific areas. The rendering proces ...

A versatile tool for creating customizable components on the fly

I am looking to create a function within my service that generates dynamic components into a ViewChild reference... I attempted to do this by: public GenerateDynamicComponent(ComponentName: string, viewContainerRef: ViewContainerRef, data?: any) { sw ...

When Vuejs removes an element from an array, it may not completely erase it from the

Trying to execute the code below, I encountered an issue where removing one item from the array did not completely remove it (other checkboxes in each row remained). I attempted using :key="index" but that did not solve the problem. However, changing :key= ...

Nested self-referencing in Typescript involves a structure where

Please note that the code below has been simplified to highlight a specific issue. The explanation before the code may be lengthy, but it is necessary for clarity. Imagine I have a Foo class that represents a complex object. interface Config { bars:{ ...

Experimenting with Typescript, conducting API call tests within Redux actions, mimicking classes with Enzyme, and using Jest

I am facing an issue where I need to mock a class called Api that is utilized within my redux actions. This class is responsible for making axios get and post requests which also need to be mocked. Despite following tutorials on how to mock axios and class ...

Checking the formik field with an array of objects through Yup for validation

Here is a snippet of the code I'm working on: https://codesandbox.io/s/busy-bose-4qhoh?file=/src/App.tsx I am currently in the process of creating a form that will accept an array of objects called Criterion, which are of a specific type: export inte ...

Accessing and sending only the body part of an HTTP response in Angular 7 test cases: A comprehensive guide

Currently, I am working on creating unit test cases in Angular 7 for a Component that utilizes an asynchronous service. This is the content of my component file: submitLoginForm() { if (this.loginForm.valid) { // send a http request to save t ...

The Vue template encountered an issue while trying to display the fetched data through ajax

I am currently working on a project that involves Vue and Axios. The console shows that Axios has a response, but for some reason, the result is not rendering on the HTML page. Can anyone provide advice on how to debug Vue? Thank you! Below is the code sni ...

Having trouble retrieving multiple parameter values with ng bootstrap modal in Angular 4

In this section, I am creating dynamic buttons that send values to an ng bootstrap modal. Currently, I am able to send and retrieve only one value. How can I modify the code to send multiple values and display them in the input field within the modal? Belo ...

What is the best way to invoke a function in a React component from another component?

I am working with a component structure that includes the Input component. In this component, there is a function called validate that is triggered by the onChange event. Here is a snippet of the code: https://i.sstatic.net/WjCLy.png import React, {FC, us ...

Display an icon before an active v-list-item in Vuetify 3's v-list

I need help figuring out how to add an icon to a v-list-item only if it is active. <v-list class="px-15 pt-5" border density="compact"> <v-list-item v-for="(item,i) in items"> <!-- Need assistance putting ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...