PASSWORD RESET

Your destination for complete Tech news

Vue

How to call a function on load in Vue JS?

646 0
< 1 min read

You can call a function when a Vue.js component is loaded by using the created() or mounted() lifecycle hooks. Here’s an example:

<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: ''
    }
  },
  created() {
    this.loadMessage();
  },
  methods: {
    loadMessage() {
      // Call an API endpoint or perform other data loading here
      this.message = 'Hello, world!';
    }
  }
}
</script>

In this example, we have a component with a message data property and a loadMessage() method. We want to call the loadMessage() method when the component is created, so we use the created() hook to do so. When the loadMessage() method is called, it sets the message property to ‘Hello, world!’. This value is then displayed in the component’s template using the mustache syntax {{ message }}.

You can also use the mounted() hook instead of created() if you need to access the DOM of the component. The mounted() hook is called after the component’s template is mounted and the component has been added to the DOM. For example, if you need to initialize a third-party library or attach event listeners to the component’s DOM elements, you can do so in the mounted() hook.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.