Executing functions in Vue TypeScript during initialization, creation, or mounting stages

Just a few hours ago, I kicked off my Vue TypeScript project. I've successfully configured eslint and tslint rules to format the code as desired, which has left me quite pleased.

Now, I'm curious about how to utilize the created/mounted lifecycle hooks in order to call a function when the application or page is refreshed. Despite reading through the documentation and attempting to implement it, I haven't had any luck so far.

<template>
  <v-app>
    <v-main>
      <p>{{ name }}</p>
    </v-main>
  </v-app>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component({
  components: {},
})
export default class App extends Vue {
  name: string = 'hello';
  
  constructor() {
    super();
    this.test();
  }
  
  onClick() {
    console.log('clicked');
    this.name = 'Clicked Hello';
  }

  test = (): void => {
    this.name = 'Hello World!';
    console.log('This is a test and it has been called');
  };

  mounted = (): void => {
    this.test();
  };

  created = (): void => {
    this.test();
  };
}
</script>

My goal is simple - to initiate a function right from the start. Although this might seem straightforward, I'm struggling with it and could really use some assistance.

I found that restarting the project and following another answer resolved the issue for me, as there were fewer warnings with the alternative approach.

Answer №1

In this code snippet, data properties are declared as functions rather than methods or hooks. It is important to note that these should not be anonymous functions because they require a bound this context.

@Component
export default class App extends Vue {
   test (): void {
      console.log('Hello')
   }

   created () {
     this.test()
   }

   mounted () {
     this.test()
   }
}

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

What methods are available to prevent redundant types in Typescript?

Consider an enum scenario: enum AlertAction { RESET = "RESET", RESEND = "RESEND", EXPIRE = "EXPIRE", } We aim to generate various actions, illustrated below: type Action<T> = { type: T; payload: string; }; ty ...

Utilizing a Custom Validator to Compare Two Values in a Dynamic FormArray in Angular 7

Within the "additionalForm" group, there is a formArray named "validations" that dynamically binds values to the validtionsField array. The validtionsField array contains three objects with two values that need to be compared: Min-length and Max-Length. F ...

I am looking to implement tab navigation for page switching in my project, which is built with react-redux and react-router

Explore the Material-UI Tabs component here Currently, I am implementing a React application with Redux. My goal is to utilize a panelTab from Material UI in order to navigate between different React pages. Whenever a tab is clicked, <TabPanel value ...

Struggling to incorporate the VueApexCharts component seamlessly into the app

Recently, I attempted to showcase some charts within my VueJS application using VueApexCharts. The installation process went smoothly, the charts were successfully added to the node_modules directory, and there were no issues with the import. Within the m ...

A guide on loading static JS files in the correct order using VueJS 2

I've come across an issue with my HTML theme that uses jQuery and a minified custom JS plugin. The application requires jQuery to be loaded before the custom plugin, but unfortunately I am unable to edit the minified plugin itself. mounted() { let ...

Unable to locate the "fcm-node" module in Node.js with TypeScript

When working on a TypeScript project, I usually rely on the fcm-node package to send Firebase push notifications in Node.js. However, this time around, I faced an issue. I know that for TypeScript projects, we also need to install type definitions (@types ...

Bringing in the Ionic ToastController to a TypeScript class

I'm unsure if it's feasible or wise, but I am currently developing an Ionic 3 project and I want to encapsulate "Toast" functionality within a class so that I can define default values and access it from any part of the application. Is there a ...

Flow error: Unable to access the value of this.props.width as the property width is not defined in T

In my React Native project, I am utilizing Flow for type checking. For more information, visit: I currently have two files named SvgRenderer.js and Cartoon.js where: Cartoon extends SvgRenderer Below is the source code for both of these files: SvgRend ...

There are no headers present in the response from apollo-client

I am currently utilizing a graphql api along with a vue.js frontend that incorporates the apollo client for fetching data from the backend. This setup has been operating smoothly thus far. In each response header, the server sends back a new JWT-Token whi ...

In search of a way to implement a conditional class binding within the current project

I am working on enhancing a child component within an existing Vue project. My goal is to allow users to add custom classes to the child component. I typically use :class="customClasses" in the dom-element for this purpose. However, there is alre ...

It appears that Typescript mistakenly interprets a class or type as a value, indicating that "'Classname' is being referred to as a value but used as a type here."

I want to pass an Object of a React.Component as "this" to a Child React.Component in the following way: component 1 file: class Comp1 extends React.Component<...,...> { ... render() { return (<Comp2 comp1={this}/> ...

Tips for capturing an error generated by a child component's setter?

I've created an App component that contains a value passed to a Child component using the @Input decorator. app.component.html <app-child [myVariable]="myVariable"></app-child> app.component.ts @Component(...) export class AppC ...

Exploiting the Power of useRef with TypeScript in Functional Components of React

I'm having trouble accessing the child component method from the parent component using useRef. Eventually, the SayHi method will be responsible for updating the hook state in the child component. Unfortunately, I am encountering some bugs that I can ...

Vue.js and TypeScript combination may result in a 'null' value when using file input

I am attempting to detect an event once a file has been uploaded using a file input. Here is the JavaScript code: fileSelected(e: Event) { if ((<HTMLInputElement>e.target).files !== null && (<HTMLInputElement>e.target).files[0] !== null) { ...

Is it possible to use TypeScript in a React Native project with a JavaScript file?

Currently, I am learning React Native by working on app clones like Instagram and YouTube. I have recently started an AirBnb clone project, but I'm facing some issues with the initial build. One issue I noticed is that in 'App.js', the temp ...

Upon loading, the IntersectionObserver immediately declares the isIntersecting property true for all elements

Yesterday, when I executed this code, everything functioned as expected. The observer successfully loaded the images once they intersected the viewport: <template> <div id="gallery" class="gallery"> <div class=" ...

Fixing "local storage not defined" issue in vue.js

While attempting to run test cases in vue.js, I encountered an error stating that local storage is not defined. Can anyone provide guidance on resolving this issue? [Login.spec.js] import Login from '../../src/Pages/Login.vue'; import{shallowMo ...

Using getters in a template can activate the Angular change detection cycle

When using getters inside templates, it seems that Angular's change detection can get stuck in a loop with the getter being called multiple times. Despite researching similar issues, I have not been able to find a clear solution. Background info: I ...

Creating Typescript types based on the values of other props: A guide

Can the TypeScript prop type be dynamically changed based on the runtime value of another prop? For instance type MyComponent = { propA: boolean | string propB: typeof propA boolean ? number : string } Is it feasible to determine the prop type of p ...

Is it possible for a redis client to function without having a redis datastore installed?

Currently in my node web server, I am utilizing the npm module known as redis. Upon executing my code... const client = redis.createClient(); client.on("error", function (err) { console.log("Error " + err); }); client.hmset(["key", "test keys 1", "t ...