代码之家  ›  专栏  ›  技术社区  ›  samynmhd

Vue重定向。我的代码是note重定向到我想要的页面

  •  1
  • samynmhd  · 技术社区  · 8 年前

    它没有重定向到该页。我在这里做错什么了?

    此方法从表单获取所有数据,并将动态值添加到日期和令牌。

    methods:{
            addToApi() {
                console.log(this.data);
                crypto.randomBytes(20,(err,buff)=>{
                    let token = buff.toString('hex');
                    let sub = this.data.sub;
                    let date = Date.now() + 3600000;
                    let newData = {
                        sub: this.data.sub,
                        token: token,
                        date: date
                    }
                    axios.post("http://localhost:3000/api/qrData",newData)
                        .then((res)=>{
    //after sending the data to back end it should redirect to this route but it doesn't redirect
                       router.go('/');
                })
                .catch((err)=>{
                    console.log(err);
                })
            })
        }
    }
    }
    
    2 回复  |  直到 8 年前
        1
  •  0
  •   Sphinx    8 年前

    检查 Vue Router: Programing Navigation ,

    正如教程所说:

    路由器.Go(n)

    这种方法需要 作为参数的单个整数 表示 在历史堆栈中前进或后退多少步, 类似 窗口。历史。开始(n) .

    对于您的用例,您应该使用 router.push

        2
  •  0
  •   Konrad Kalemba    8 年前

    主要的问题是 this 在这种情况下在作用域上具有不同值的变量。常见的解决方案是创建一个新的变量存储 这 就像我在第一行做的那样 addToApi() 方法。

    说到重点,变量 router 在方法的作用域中未定义。你应该用 this.$router 指的是全局路由器对象。作为 这 变量在中丢失其值 then 函数(范围更改),您要使用 vm 我定义的变量。所以您的代码最终应该如下所示:

    如注释所示,箭头函数不携带 这 变量。

    如果要重定向到应使用的特定路由 $router.push 方法代替。( go method was used in Vue Router's older versions and renamed to push in 2.x )

    methods: {
      addToApi() {        
        crypto.randomBytes(20, (err, buff) => {
          let token = buff.toString('hex');
          let sub = this.data.sub;
          let date = Date.now() + 3600000;
          let newData = {
            sub: this.data.sub,
            token: token,
            date: date
          }
          axios.post("http://localhost:3000/api/qrData", newData)
            .then((res) => {
              //after sending the data to back end it should redirect to this route but it doesn't redirect
              this.$router.push('/');
            })
            .catch((err) => {
              console.log(err);
            })
        })
      }
    }
    }
    
    推荐文章