Vue Router - 路由加载后调用函数

RJ *_*ain 8 javascript vue.js vue-router

我正在处理一个项目,我需要在路由完成加载后调用一个函数。但是,使用“监视”功能时,它仅在路线更改时加载,但会在路线完成加载之前加载。因此,当我尝试运行以页面上的 DOM 元素为目标的脚本时,这些元素尚不存在。Vue Router 中是否有任何功能可以让我在运行脚本之前等待所有内容都呈现出来?

const app = new Vue({
    el: '#app',
    router,
    watch: {
        '$route': function (from, to) {
            function SOMEFUNCTION()
         }   
    },
    data: {
        some data
    },
    template: `
      <router-view/>
  `
})
Run Code Online (Sandbox Code Playgroud)

Tof*_*del 6

你应该使用Vue.nextTick

在你的情况下,这将转化为:

const app = new Vue({
    el: '#app',
    router,
    watch: {
        $route() {
            this.$nextTick(this.routeLoaded);
         }   
    },
    data() {
        return {};
    },
    methods: {
        routeLoaded() {
           //Dom for the current route is loaded
        }
    },
    mounted() {
/* The route will not be ready in the mounted hook if it's component is async
so we use $router.onReady to make sure it is.
it will fire right away if the router was already loaded, so catches all the cases.
Just understand that the watcher will also trigger in the case of an async component on mount
because the $route will change and the function will be called twice in this case,
it can easily be worked around with a local variable if necessary
*/
       this.$router.onReady(() => this.routeLoaded());
    },
    template: `<router-view/>`
})
Run Code Online (Sandbox Code Playgroud)

这将在每次路由更改时调用routeLoaded方法(我推断这是您使用该<router-view>元素时所需要的),如果您也想最初调用它,我会推荐安装挂钩(如示例中所示)或观察者上的立即标志


小智 -1

您可以通过连接 VueJS 来完成此操作lifecycle hooks

  1. 使用 VueJS 生命周期挂钩:以下是主要 VueJS 生命周期挂钩的摘要。请参阅文档以获取完整说明。

我。beforeCreate:该函数会在组件创建之前调用

二. created:该函数会在组件创建后调用,但注意虽然组件已创建,但尚未挂载。因此您将无法访问该this组件的。Network Requests然而,这是更新数据属性的好地方。

三. mounted:一旦组件被渲染并且可以在此处访问元素,就会调用此函数。这就是您要找的。

四. beforeDestroy:该函数在组件被销毁之前调用。这对于停止您创建的任何侦听器(setTimeout、setInterval..)很有用。

See the diagram below for the details.

const app = new Vue({
    el: '#app',
    router,
    mounted(){
      this.someFunction()
    },
    data: {
        some data
    },
    template: `
      <router-view/>
  `
})
Run Code Online (Sandbox Code Playgroud)
  1. 使用 Vue Router 导航守卫:Vue Router 还公开了一些您可以挂钩的生命周期挂钩。然而,正如您将在下面看到的,它们不符合您的要求:

我。beforeRouteEnter:在确认渲染该组件的路由之前调用。oe 无法访问this组件实例,因为调用此守卫时它尚未创建!

二. beforeRouteUpdate:当渲染该组件的路由发生变化,但该组件在新路由中被重用时调用。

三. beforeRouteLeave:当渲染该组件的路由即将被导航离开时调用。

在此输入图像描述

参考:

VueJS 文档(生命周期):VueJS 实例

Vue Router 文档(Navigation Guards):Navigation Guards

  • 当涉及到 vue 路由器时,钩子是不够的,因为在应用程序中导航时,路线会改变,但钩子不会再次触发 (4认同)