【问题标题】:Vue.js router not calling beforeRouteUpdate (typescript)Vue.js 路由器未调用 beforeRouteUpdate(打字稿)
【发布时间】:2018-08-20 12:23:44
【问题描述】:

我有一个组件,其中包含指向同一路由的路由器链接,但参数不同。导航到这些链接时,网址会更改,但数据不会更新。我已经定义了 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;
            });
    }
}

【问题讨论】:

    标签: typescript vuejs2 vue-component vue-router


    【解决方案1】:

    在提出问题 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 获取 slug 之前。相反,我将所有内容都放在mounted中它自己的函数中,然后使用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) {
        //...
      }
    

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

    【讨论】:

      【解决方案2】:

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

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

      Component.registerHooks([
          'beforeRouteEnter',
          'beforeRouteLeave',
          'beforeRouteUpdate',
      ]);
      
      new Vue({...});
      

      【讨论】:

      • 在 index.ts 而不是 .vue 文件中??
      • 谢谢 Erik 和 Simsteve7,他们帮了大忙。首先,我想到了我使用过的 SSR 中的问题,并尝试在 VueRouter 文档上搜索信息。但后来我发现了这个问题,并明白问题出在打字稿中(这里也有描述github.com/vuejs/vue-class-component#adding-custom-hooks
      猜你喜欢
      • 2019-01-20
      • 2019-02-18
      • 2018-09-29
      • 2020-09-26
      • 1970-01-01
      • 2023-01-03
      • 2022-11-25
      • 1970-01-01
      • 2017-11-09
      相关资源
      最近更新 更多