如何在Vue中提交表单,重定向到新路线并传递参数?

JavaScript Vue.js

阿飞

2020-03-20

我正在使用Nuxt和Vue,并且尝试提交表单,将用户重定向到包括提交的参数的新路线,发送API请求以获取一些数据,然后呈现该数据。

通过将表单操作设置为新路径,然后将所有URL参数手动添加到API请求中,我实现了这一点。

首先,我使用route创建一个简单的表单/search

<form action="/search">
  <input type="text" name="foobar">
  <button type="submit">Submit</button>
</form>

提交表单时,用户离开当前页面并被重定向到新页面。该网址现在看起来像这样:http://www.example.com/search?foobar=test现在,我foobar通过使用获取参数this.$route.query.foobar并将其发送到我的API。

但是,我的方法的问题是,在提交表单时,用户将离开当前页面,并且将发生新的页面加载。在构建渐进式Web应用程序时,这不是我们想要的。

所以我的问题是如何在Nuxt / Vue中提交表单并重定向到包含提交的参数的新路径?

第2540篇《如何在Vue中提交表单,重定向到新路线并传递参数?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
小哥逆天 2020.03.20

的默认行为<form>是重新加载页面onsubmit实施SPA时,最好避免调用的默认行为<form>

Making use of router module which is available out-of-box in nuxtjs will enable all the redirection controls to flow within the application. if we try to trigger events available via <form> then browser reload will occur. This has to be avoided.

So my question is how can I submit a form in Nuxt/Vue and redirect to a new route including the submitted parameters?

You can try below approach

First

Use .stop.prevent modifiers to prevent the submit button from invoking default <form> behavior. This is similar to using event.stopPropagation(); and event.preventDefault(); in jQuery

<form>
  <input type="text" name="foobar" v-model="foobar">
  <button type="submit" @click.stop.prevent="submit()">Submit</button>
</form>

Then

Create

  1. vue model object foobar

  2. vue method submit

使用this.$router.push重定向到下一个页面。这将使控制流停留在SPA内。如果要将数据发送到服务器,则可以在调用this.$router.push 其他数据之前先进行处理,然后可以重定向并继续执行逻辑。

export default {
    data(){
      return {
        foobar : null
      }
    },
    methods: {
      submit(){
         //if you want to send any data into server before redirection then you can do it here
        this.$router.push("/search?"+this.foobar);
      }
    }
  }
神乐乐 2020.03.20

只需添加:@ submit.prevent =“ false”

<form @submit.prevent="false">
      <div class="form-group">

      </div>   
 </form>

我希望这对你有用:)

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android