Vue路由器将我的路线参数ID加一 [英] Vue router incrementing my route params id by plus one

查看:275
本文介绍了Vue路由器将我的路线参数ID加一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to change the id in my route by plus one of the current id whenever you press on a button. I am building a questionaire with True / false buttons and whenever a user presses a button it should go to the next id like so /question/1 > /question/2. I have tried returning the current this.$route.params.id++ in my computed lifecycle hook, like so:

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 + 1;替换return this.$route.params.id++;,但这(在逻辑上)只是将数字添加到末尾而不是递增.

I've tried also to replace return this.$route.params.id++; with return this.$route.params.id + 1; but this (logically) just adds the number to the end instead of incrementing it.

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

What would be the right way to approach this?

推荐答案

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

I had the same issue. Turns out Vuex automatically parses this.$route.params.id as string instead of Number. I solved it by using javaScript Number() method. In your case this would be:

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

或者说您的路线视图为post/question/1,您可以像这样向按钮添加处理程序:@click="$router.push(nextQuestion)"然后在计算的生命周期挂钩中执行以下操作:

or alternatively say your route view is post/question/1, you can add a handler to your button like so: @click="$router.push(nextQuestion)"then in your computed lifecycle hook, do this:

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

这篇关于Vue路由器将我的路线参数ID加一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆