Vue.js 路由器不调用 beforeRouteUpdate(打字稿)

Eri*_*rik 8 typescript vue-router vue-component vuejs2

我有一个组件,其中包含指向同一路由的路由器链接,但具有不同的参数。导航到这些链接时,url 会更改,但数据不会更新。我已经定义了beforeRouteUpdate,但它从未被调用。

import Vue from 'vue';
import { Component } from 'vue-property-decorator';
@Component
export default class AccountComponent extends Vue {
    address: string;
    account: Account;

    data() {
        return {
            account: null
        }
    }

    beforeRouteUpdate(to: any, from: any, next: any) {
        console.log('beforeRouteUpdate for ' + to.params.address);
        next();
    }

    mounted() {
        this.address = this.$route.params.address;
        this.loadData();
    }

    loadData() {
        console.log('Fetching data for ' + this.address);
        fetch('api/Account/Get?address=' + this.address)
            .then(response => response.json() as Promise<Account>)
            .then(data => {
                this.account = data;
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

rba*_*all 9

在提出问题 2 年后,我自己就遇到了这个问题,但除了 Simsteve7 的回答之外,我还需要将该代码放在它自己的文件中

// router/componentHooks.ts

import Component from "vue-class-component";

// Register the router hooks with their names
Component.registerHooks([
    "beforeRouteEnter",
    "beforeRouteLeave",
    "beforeRouteUpdate"
]);
Run Code Online (Sandbox Code Playgroud)

然后在 main.ts 中导入它的第一行。

import './router/componentHooks' // <-- Needs to be first
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
Run Code Online (Sandbox Code Playgroud)

在我刚刚安装组件的调用并通过 this.$route.params 获取 slug 之前。取而代之的是,我将所有内容都放在了它自己的函数中,然后使用 this.$route.params 和 beforeRouteUpdate 的 to.params 从mounted 中调用了它。举个例子:

  async mounted() {
        await this.loadPage(this.$route.params.id)
  }

  async beforeRouteUpdate(to, from, next) {
        console.log(`beforeRouteUpdate ${to.params.id}`)
        await this.loadPage(to.params.id)
    next()
  }

  async loadPage(id) {
    //...
  }
Run Code Online (Sandbox Code Playgroud)

来源:https : //class-component.vuejs.org/guide/additional-hooks.html


Ste*_*ris 6

由于仍然没有答案,我将发布一个可能的问题。

确保beforeRouteUpdate在初始化 Vue 之前注册钩子。

Component.registerHooks([
    'beforeRouteEnter',
    'beforeRouteLeave',
    'beforeRouteUpdate',
]);

new Vue({...});
Run Code Online (Sandbox Code Playgroud)