【问题标题】:Vue router incrementing my route params id by plus oneVue路由器将我的路由参数ID加一
【发布时间】:2020-07-03 20:09:04
【问题描述】:

每当您按下按钮时,我都会尝试通过加上一个当前 id 来更改路线中的 id。我正在构建一个带有真/假按钮的问卷,每当用户按下一个按钮时,它都应该转到下一个 ID,例如 /question/1 > /question/2。我尝试在计算的生命周期挂钩中返回当前的this.$route.params.id++,如下所示:

nextQuestion() {
   return this.$route.params.id++;
}

但这会导致以下错误:

Unexpected side effect in "nextQuestion" computed property

我的<router-link> 看起来像这样:

<router-link :to="`/question/${nextQuestion}`">
...
</router-link>

我也尝试将 return this.$route.params.id++; 替换为 return this.$route.params.id + 1; 但这(逻辑上)只是将数字添加到末尾而不是增加它。

解决这个问题的正确方法是什么?

【问题讨论】:

  • return parseInt(this.$route.params.id)+1 所以你不会改变参数而是返回一个变异的副本。
  • return this.$route.params.id + 1; 应该可以正常工作,这不是您想要的吗?当用户点击链接时,他将进入下一个问题。

标签: vue.js parameters vue-router increment router


【解决方案1】:

我遇到了同样的问题。结果 Vuex 自动将 this.$route.params.id 解析为字符串而不是数字。我通过使用 javaScript Number() 方法解决了它。在您的情况下,这将是:

nextQuestion() {
   return (Number(this.$route.params.id++));
}

或者说你的路由视图是post/question/1,你可以像这样向你的按钮添加一个处理程序:@click="$router.push(nextQuestion)"然后在你计算的生命周期钩子中,这样做:

nextQuestion() {
    return "post/question/"  + (Number(this.$route.params.id) + 1)
}

【讨论】:

    猜你喜欢
    • 2021-05-06
    • 2019-07-24
    • 1970-01-01
    • 2018-04-30
    • 2019-05-24
    • 2019-12-14
    • 1970-01-01
    • 2020-04-30
    • 2021-11-06
    相关资源
    最近更新 更多