【问题标题】:How do I navigate once I submit a form and receive a status of 200提交表单并收到状态 200 后如何导航
【发布时间】:2019-12-10 13:45:30
【问题描述】:

一旦我的数据成功提交,我对如何从表单路由导航到另一个路由感到困惑。

我找到了this example。 看起来它应该可以工作,但在 Vue 路由器方面有点不清楚,如果我已经有一个路由组件,我可以在任何组件中实例化一个新的 Vue 路由器。无论如何,它似乎获得了状态,但它并没有推送路由。

我的方法:

methods: {
  handleSubmit(event) {
    const router = new VueRouter();
    axios.post(API_ENDPOINT,
    this.itemInit,
    { headers: {
      'Content-type' : 'application/json',
       }
    }).then(response => {
        this.results = response.data.results;
        if(response.status == 200) {
          router.push('/');
        }
    }).catch(error => {console.log(error)});
  }
}

当我从服务器获得状态 200 时,我希望它导航到根路由,我就是这样,一切正常,只是没有得到这个导航。

更新:这对我有用。

methods: {
  handleSubmit(event) {
    const router = new VueRouter();
    axios.post(API_ENDPOINT,
    this.itemInit,
    { headers: {
      'Content-type' : 'application/json',
       }
    }).then(response => {
        this.results = response.data.results;
        if(response.status == 200) {
          this.$router.push('/');
        }
    }).catch(error => {console.log(error)});
  }
}

【问题讨论】:

  • 您能否发布您的 main.js 文件(您的应用程序的入口点)。我假设您在创建应用程序时会将路由器附加到新的 Vue 实例?
  • 我可以发誓我在发布之前添加了几次尝试,但添加了 this.$router.push('myRoute');工作。也许这篇文章会帮助别人。
  • 是的!我在下面发布了基本设置,以举例说明将路由器安装到 Vue 实例,然后引用就像您在评论中发布的那样......就像您回贴一样。很高兴你已经启动并运行了!

标签: vue.js axios vue-router


【解决方案1】:

假设您正在入口点(通常是 main.js)中构建单页应用程序

你会做类似以下的事情:

import Vue from 'vue'
import { router } from '@/plugins/vue-router' // This is where you declare your routes

当你启动你的应用程序时,你会得到类似的东西:

new Vue({
  el: '#app',
  router,
  template: '<App/>'
})

现在在您的组件中,您需要将代码更新为:

methods: {
  handleSubmit(event) {
    axios.post(API_ENDPOINT,
    this.itemInit,
    {
      headers: {
        'Content-type' : 'application/json',
      }
    }).then(response => {
      this.results = response.data.results;
      if(response.status == 200) {
        this.$router.push('/');
      }
    }).catch(error => {console.log(error)});
  }
}

【讨论】:

  • 谢谢!我最终也找到了您的解决方案。
猜你喜欢
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2013-12-27
相关资源
最近更新 更多