Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs - How to call a method on load event on element

I want to call on load event on element when it being loaded in for loop using vuejs. I have found onload event on page load, but I can't find anyway to do that with element. Here is my code, but it's not working.

<ul>
  <li v-for="(option,opt_index) in question.options" v-on:load="test">
  Testing
  </li>
</ul>

Here is my component.

import VueSweetalert2 from 'vue-sweetalert2';

Vue.use(datePicker);
Vue.use(VueSweetalert2);
Vue.use(VeeValidate);

export default {
    name: "modal",
    components: {
        draggable,
    },
    mounted() {
    },
    methods: {
        test(){
            alert('load');
        }
    }
}
like image 690
aftab hussain Avatar asked Jan 11 '19 07:01

aftab hussain


People also ask

How do you call a method on page load in Vue?

We can call a Vue. js method on page load by calling it in the beforeMount component hook. We can also make a method run on page load by calling it in the created hook. And we can do the same in the mounted hook.

Which lifecycle function is first called when a Vue app is loaded in the DOM?

beforeCreate() This is the very first lifecycle hook that gets called in Vue JS, it gets called immediately after the Vue instance has been initialized.


1 Answers

That's because a list item (li) does not emit a native load event. The next best thing you can do is wait for Vue's next rendering cycle to finish and then call your method. That way you're guaranteed that the whole loop has finished rendering.

In order to wait for the rendering cycle to finish, we need to use Vue's nextTick() utility method:

import VueSweetalert2 from 'vue-sweetalert2';

Vue.use(datePicker);
Vue.use(VueSweetalert2);
Vue.use(VeeValidate);

export default {
    name: "modal",
    components: {
        draggable,
    },
    mounted() {
      this.$nextTick(() => {
        this.test();
      });
    },
    methods: {
        test(){
            alert('load');
        }
    }
}

In this example, we use nextTick's callback version. There's also a promise-based version:

mounted() {
  this.$nextTick().then(this.test);
}

Or if you're familiar with async/await:

async mounted() {
  await this.$nextTick();
  this.test();
}

Note that this does not fire the test method for each question.options item. If you wish to do that, I guess your only option is to still use nextTick and then inside test loop through question.options once more and call a method for each option.

If you provide some more background on what you're trying to achieve, maybe we can find a more optimal route.

PS! Welcome to StackOverflow 👋

like image 150
kano Avatar answered Oct 13 '22 20:10

kano