我有一个组件,其中包含指向同一路由的路由器链接,但具有不同的参数。导航到这些链接时,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;
});
}
}
答案 0 :(得分:5)
问了问题2年后,我自己就遇到了这个问题,但是除了Simsteve7的回答,我还需要将该代码放在它自己的文件中
// router/componentHooks.ts
import Component from "vue-class-component";
// Register the router hooks with their names
Component.registerHooks([
"beforeRouteEnter",
"beforeRouteLeave",
"beforeRouteUpdate"
]);
然后在main.ts中导入的第一行。
import './router/componentHooks' // <-- Needs to be first
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
在我刚刚挂载组件的调用之前,正在通过this。$ route.params来处理。取而代之的是,我将所有内容放入其自己的函数中的mount中,然后使用this。$ route.params和beforeRouteUpdate的to.params从mount中调用它。举个例子:
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) {
//...
}
来源:https://class-component.vuejs.org/guide/additional-hooks.html
答案 1 :(得分:0)
由于仍然没有答案,我将发布一个可能的问题。
在初始化Vue之前,请确保注册beforeRouteUpdate
钩子。
Component.registerHooks([
'beforeRouteEnter',
'beforeRouteLeave',
'beforeRouteUpdate',
]);
new Vue({...});