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');
}
}
}
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.
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.
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 👋
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With