Sunday, November 23, 2025
HomeLanguagesJavascriptHow to set a click event once a page or view is...

How to set a click event once a page or view is loaded in vue.js?

In this article, we will discuss how to set a click event once a page or view is loaded in vue.js. Just like every other JavaScript framework Vue also supports the Mounting hooks. Mounting hooks are often the most used hooks. They allow us to access or modify the DOM of your component just before or after the first render. 

So, here we will use the mounted hook to trigger a click event when the page is loaded.

Step to setup the Environment:

  1. First, we should install vue.js by using the command below:

    sudo npm install -g @vue/cli
  2. After, installing the vue.js. you can create a new project by using the command below:

    vue create test
  3. Now, Go to your project folder by using

    cd myapp
  4. You can run your project using the command below:

    npm run serve

The file structure of your project will look like this:


Syntax

  • Step-1: Give a reference to the button you want to click.
    <button ref="Btn" @click="logClicked">Click</button>
  • Step-2: In the mounted hook trigger the button click.
    mounted () {
      this.$refs.Btn.click()
    }

Example: Open your App.vue file from the test project src folder and update the code.

Javascript




<script>
export default({
  methods: {
    logClicked () {
      console.log('Clicked')
    }
  },
  mounted () {
    this.$refs.Btn.click()
  }})
</script>
<template>
<div id="app" class="container">
  
  <button ref="Btn" @click="logClicked">Click</button>
</div>
</template>


OutputFor can see the output in chrome by typing localhost:8080 also open the console in your Chrome browser by using the command below

 ctrl+shift+j

RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6864 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS