Vue.js路由器:组件就绪后运行代码 [英] Vue.js Router: Run code when component is ready

查看:60
本文介绍了Vue.js路由器:组件就绪后运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Vue.js及其官方路由器开发单页应用程序.

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

我使用路由器加载的每个部分都有一个菜单和一个组件(.vue文件).在每个组件中,我都有一些类似于以下的代码:

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>

一旦组件完成转换,我想执行一段代码(初始化jQuery插件).如果我将代码添加到 ready 事件中,则仅在第一次执行时触发该代码.组件已加载.如果我将代码添加到 route.activate 中,它每次都会运行,这很好,但是尚未加载DOM,因此无法初始化我的jQuery插件.

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.

每当组件完成转换并准备好其DOM时,如何运行我的代码?

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

推荐答案

在使用Vue.js路由器时,这意味着每次转换到新路由时,Vue.js将需要更新DOM.默认情况下,Vue.js异步执行DOM更新.

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.

为了等到Vue.js完成更新DOM,可以使用Vue.nextTick(callback).DOM更新后将调用回调.

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.

您可以尝试以下方法:

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

有关更多信息:

这篇关于Vue.js路由器:组件就绪后运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆