The initialization function is not being invoked

I've set up a new project using vue ui with typescript, babel, and a linter. Everything seems to be working smoothly, except I'm running into some confusion with implementing the Composition API's setup method. For some reason, it doesn't seem to be getting called (no output in the log). I'm currently stuck on this issue.

  • vue: 3.0.0-rc.10

  • vue-cli: 4.5.4

    <script lang="ts">
     import { Options, Vue } from 'vue-class-component'
     import HelloWorld from './components/HelloWorld.vue'
    
     @Options({
       components: {
         HelloWorld
       },
       setup () {
         console.log('SETUP HERE')
       }
     })
     export default class App extends Vue {
       setup () {
         console.log('SETUP THERE')
       }
     }
     </script>
    

Answer №1

To make use of the setup method from the vue-class-component library, you should follow these steps:

<template>
  <div>Count: {{ counter.count }}</div>
  <button @click="counter.increment()">+</button>
</template>

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

function useCounter () {
  const count = ref(0)

  function increment () {
    count.value++
  }

  onMounted(() => {
    console.log('onMounted')
  })

  return {
    count,
    increment
  }
}

export default class Counter extends Vue {
  counter = setup(() => useCounter())
}
</script>

For more information, you can refer to this link

Answer №2

I encountered a similar issue where extending the child component caused some complications. It seems that the composition API (setup method) is not invoked when extending a component, unlike the options API lifecycle hooks which are triggered in both components.

// child.js

<script>
import { onMounted } from "vue";

export default {
  name: "ChildComponent",
  setup() {
    console.log('Child - setup()');
    onMounted(() => {
      console.log('Child - mounted (composition API)');
    })
  },
  mounted() {
    console.log('Child - mounted (option API)');
  }
}
</script>
// parent.js

<script>
import ChildComponent from "./child.js";
import { onMounted } from "vue";

export default {
  name: "ParentComponent",
  extends: ChildComponent,
  setup() {
    console.log('Parent - setup()');
    onMounted(() => {
      console.log('Parent - mounted (composition API)');
    })
  },
  mounted() {
    console.log('Parent - mounted (option API)');
  }
}
</script>

OUTPUT

Parent - setup()
Parent - mounted (composition API)
Child - mounted (option API)
Parent - mounted (option API)

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

Exploring the use of .pipe with Angular Jest for testing

Currently, I am trying to test the following .ts file: create(entityResourceID, params: any): Observable <any>{ const url = `${this.apiUrl}/${entityResourceID}/assignee`; return this.http.post(url, params).pipe( map(() ...

A Error occurs if ReactQuill is used without defining the document object

Recently, I embarked on a journey with both next.js and ReactQuill. However, upon running yarn build, an unexpected obstacle arose: info Creating an optimized production build - info Compiled successfully - info Linting and checking validity of types - in ...

Discover the secret to applying a gradient shade to the "border" element when it reaches full capacity with Vue's innovative Custom CSS package

Utilizing the package https://www.npmjs.com/package/vue-css-donut-chart#usage-with-all-the-available-props to create a "border" effect around images based on progress has presented a challenge. Specifically, achieving a gradient color for the border when i ...

How To Retrieve the Index of a Specific Row and Column in AgGrid (Angular)

Right now, I can retrieve the row data using the gridApi but I am struggling to determine the column index of the selected row. The method this.gridApi.getSelectedRows() does not provide any information about the column index. I would greatly appreciate ...

Incorporate a 'Select All' functionality into ion-select by adding a dedicated button

Looking for a way to set custom buttons on ion-select through interfaceOptions in ionic 4? HTML <ion-item> <ion-label>Lines</ion-label> <ion-select multiple="true" [(ngModel)]="SelectedLines" [interfaceOptions]="customAlertOption ...

Error Encountered: RSA Key Pairs Invalid Signature for JSON Web Token (JWT)

I am facing an issue with my Node.js application (version 20.5.1) regarding the verification of JSON Web Tokens (JWT) using RSA key pairs. The specific error message I am encountering is: [16:39:56.959] FATAL (26460): invalid signature err: { "type& ...

The process of dynamically loading and changing Vuetify Tabs is a dynamic and versatile feature

I'm currently implementing Vuetify Tabs to showcase my items. The Tabs are being utilized to exhibit a swipeable list of items that can be approved or disapproved by the user. Once an item is approved, it should be removed from the list. However, I&a ...

Issues with manipulating state using TypeScript Discriminated Unions"Incompatibility with setState

Imagine having a unique type structure like the one shown below: export type IEntity = ({ entity: IReport setEntity: (report: IReport) => void } | { entity: ITest setEntity: (test: ITest) => void }); Both the entity and setEntity fun ...

Creating Class Names Dynamically in Angular 2 Using ngFor Index

Encountering an issue while trying to generate a dynamic class name based on the ngFor loop index in Angular 2. Due to restrictions, I had to use a specific syntax as Angular 2 does not support ngFor and ngIf together on the same element. Given this setup ...

The 'RouterLink' JSX element type is missing any construct or call signatures

While researching this issue on the internet and Stack Overflow, I've noticed a common theme with problems related to React. An example can be found here. However, I am working with Vue and encountering errors in Vue's own components within a new ...

Enhance the appearance of Google Maps by incorporating gradient effects, box shadows, or other similar visual

How can I add a linear gradient to Google Maps? Below is my code snippet. HTML <div id="map"></div> CSS #map{ height:100vh; background: linear-gradient(90deg, #f7f8fa 0%, rgba(247, 248, 250, 0) 18.73%), linear-gradient(180deg, # ...

"Vue.js Mustache Syntax: Beautifying Data Binding with Curly Br

Each element object in my list array has been numbered using the row index as shown below: {{tableData[props.index-1] = props.index }} The code above worked perfectly fine. Initially, I assumed that it would be the left side value (tableData[props.index ...

Associating function parameters with object types in TypeScript

In the conclusion of this post, I provide operational code for associating object types with a function that accepts an object containing matching properties. The code snippet I shared results in 'result' being resolved as: type result = { GE ...

Error TS2322: Type 'Partial<T>' is not assignable to type 'T'

I'm struggling to articulate my problem, so I think the best way to convey it is through a minimal example. Take a look below: type Result = { prop1: { val1: number, val2: string }, prop2: { val1: number } }; f ...

unable to locate the sw.js file in the Vue plugin PWA

My experience with using the vue PWA plugin has been positive so far. I have one app that works great with it. The configuration for this app in VueJS looks like this: const WebpackNotifierPlugin = require('webpack-notifier') module.exports = { ...

What could be causing my if statement to fail even though the condition is met?

I'm attempting to generate dynamic fields based on my chosen attributes. I have two array objects called addAttributes and fakeAttributes. The fakeAttributes contain the details of the selected attributes. I have a dropdown select component that displ ...

Guide on implementing the Translate service pipe in Angular 2 code

So here's the issue... I've integrated an Angular 4 template into my application which includes a functioning translate service. The only problem is, I'm unsure of how to utilize that pipe in my code. In HTML, it's as simple as adding ...

Struggling to access the properties of a Material-UI Button

import * as React from "react"; import { styled } from "@mui/material/styles"; import MuiButton from "@mui/material/Button"; import Slider from "@mui/material/Slider"; interface Props { type: "primary" | ...

Separate the string by commas, excluding any commas that are within quotation marks - javascript

While similar questions have been asked in this forum before, my specific requirement differs slightly. Apologies if this causes any confusion. The string I am working with is as follows - myString = " "123","ABC", "ABC,DEF", "GHI" " My goal is to spli ...

Substituting JSON objects with alphabets

When running this code, the expected output will display the name and the choices. To clarify, I aim to substitute the values of Not effective, Neither effective nor Effective, Effective with "A", "B", and "C", respectively. ...