Vue.js Router: Run code when component is ready

て烟熏妆下的殇ゞ 提交于 2019-12-19 09:47:43

问题


I'm working on a single-page app with Vue.js and its official router.

I have a menu and a component (.vue file) per every section which I load using the router. In every component I have some code similar to this:

<template>
    <div> <!-- MY DOM --> </div>
</template>

<script>
    export default {
        data () {},
        methods: {},
        route: {
            activate() {},
        },
        ready: function(){}
    }
</script>

I want to execute a piece of code (init a jQuery plugin) once a component has finished transitioning in. If I add my code in the ready event, it gets fired only the first time the component is loaded. If I add my code in the route.activate it runs every time, which is good, but the DOM is not loaded yet, so is not possible to init my jQuery plugin.

How can I run my code every time a component has finished transitioning in and its DOM is ready?


回答1:


As you are using Vue.js Router, it means that each time you will transition to a new route, Vue.js will need to update the DOM. And by default, Vue.js performs DOM updates asynchronously.

In order to wait until Vue.js has finished updating the DOM, you can use Vue.nextTick(callback). The callback will be called after the DOM has been updated.

In your case, you can try:

route: {
    activate() {
        this.$nextTick(function () {
            // => 'DOM loaded and ready'
        })
    }
}

For further information:

  • https://vuejs.org/api/#Vue-nextTick
  • https://vuejs.org/guide/reactivity.html#Async-Update-Queue



回答2:


You can use

mounted(){
  // jquery code
}



回答3:


Though this may be a bit late... If I guess correctly, the component having problem stays on the page when you navigate between routes. This way, Vue reuses the component, changing what's inside it that needs to change, rather than destroy and recreate it. Vue provides a key attribute to Properly trigger lifecycle hooks of a component. By changing a component's key, we can indicate Vue to rerender it. See key in guide for details and key in api for code sample.



来源:https://stackoverflow.com/questions/38363294/vue-js-router-run-code-when-component-is-ready

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!