【问题标题】:@Watch('$router') is not fired and throws exception@Watch('$router') 未被触发并引发异常
【发布时间】:2019-11-29 18:40:36
【问题描述】:

我正在深入研究 Vue + Typescript。在我遇到路由器问题之前一直很好。

我的应用结构是:

  1. AppComponent(根)
  2. HomeComponent(放置在路由器视图内)
  3. RequestsComponent(包含 10 个请求的表。每个请求由 #4 表示)
  4. RequestsRowComponent

RequestsComponent 包含一个分页控件,因此用户可以单击按钮,路由将更改为 /page/1、/page/2、/page/...

我已经尝试使用内部路由,更改捕获路由更改的组件以及类似的所有内容。

发现了一些组件可能已经被销毁的信息,但这很奇怪,因为我在不同的组件中使用了这个@Watch。例如。根 AppComponent 根本不应该被销毁。

我用的是 VS2019。

路线配置:

const routes = [
    {
        path: '/', redirect: async (to: Route) => {
            await RedirectToLanguage();
        }
    },
    { path: '/:lang', redirect: '/:lang/page/1' },
    { path: '/:lang/page/:page', component: require('./components/home/home.vue.html') },
];

...

Requests.ts

    @Watch('$route')
    onPageChanged() {
        this.page = Number(this.$route.params['page']);
        this.refreshRequestList();
    }

我希望@Watch('$route') 指令能够捕获 RequestsComponent 和 AppComponent 中的路由变化。实际上,代码不会到达@Watch 方法(或者并非总是如此,在某些修复过程中,断点被命中,但不是 100%)。我也在控制台中收到错误:

观察者“$route”的回调错误:“TypeError: Cannot read property 'call' of undefined”

发现于

---> 在 \ClientApp\components\requestRow\requestRow.vue.html

在 \ClientApp\components\requests\requests.vue.html

在 ClientApp\components\home\home.vue.html

在 ClientApp\components\app\app.vue.html

我相信 cb 是“回调”,我不确定如何未定义方法。 requestRow 在日志中也很奇怪。

我已经面对它很长时间了,因此非常感谢任何帮助。有人可以解释如何调试此问题以及根本原因是什么?谢谢。

【问题讨论】:

    标签: typescript vue.js vue-router


    【解决方案1】:

    这是因为所有这些路由都解析为同一个组件。这里有两个选项:

    @Watch('$route.params.page') onPageChanged() { ... }
    

    或者:

    <router-view :key="$route.name + ($route.params.page || '')">
    

    这将强制路由完全更新,因为动态页面属性已更改。

    【讨论】:

    • 第一个选项不起作用,这就是问题所在。所以我通过使用 :key=$route. 将动态内容分隔到一个单独的组件来修复它。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2012-11-18
    • 2019-11-02
    • 2014-12-31
    • 1970-01-01
    • 2012-10-10
    • 2019-07-10
    • 2015-03-08
    • 2019-03-02
    相关资源
    最近更新 更多