Skip to content
Related Articles

Related Articles

How to set a click event once a page or view is loaded in vue.js?
  • Last Updated : 22 Jan, 2021

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


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

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :