在vuejs中登录组件

时间:2018-02-22 01:12:59

标签: javascript vue.js

我已经使用以下代码构建了一个登录组件,以便用户登录后端,并使用flask_login。

const LoginScreen = {

    template: `
                <div>
                    <h1>Sign In</h1>
                    <form id="loginform" class="pure-form">
                        <fieldset>
                            <input type="text" name="email" placeholder="email" v-model="logindetails.email"/>
                            <input type="password" name="password" placeholder="password" v-model="logindetails.password"/>
                            <button class="pure-button pure-button-primary" v-on:click="login">Login</button>
                        </fieldset>
                    </form>
                </div>
    `,

    data: function () {
        return {
                logindetails:{}
        }
    },

    methods: {
                login: function(){
                                    axios.post('/login/',
                                        this.logindetails,
                                           {
                                             headers: {
                                                        'Content-type': 'application/json',
                                                        'Accept': 'application/json',
                                                        'X-CSRF-TOKEN': document.querySelector('#csrftoken').getAttribute('content')
                                                       }
                                           }
                                          ).then(response => { this.logindetails = {};
                                                               this.$router.push({path: '/'});
                                                             }
                                                )
                                           .catch(function (error) {
                                                              console.log(error);
                                                            });
                                    }
            }
};

它似乎工作正常(虽然有时它要求我再次登录似乎没有理由),但组件将提交的表单详细信息放入url(example)的查询字符串中。

是否有人能够告诉我我做错了什么,或者如果我这样做完全错误,请指向正确登录的代码库/指南的方向?

非常感谢提前。

2 个答案:

答案 0 :(得分:2)

查看Vue v-on event modifiers以修改默认元素行为。

在您的情况下,您可以这样做:

<button @click.prevent="login">Login</button>

或者在表单标签中(确保您的提交按钮是“提交”类型):

<form @submit.prevent="login">

答案 1 :(得分:1)

关于the component is putting the submitted form details into the querystring of the url,原因是点击该按钮也会触发表单上的submit

HTML表单将表单值提交给服务器。

但通常在像Vue或React这样的JS框架中,表单值通过ajax提交,没有任何页面刷新。所以使用<form>在这里没什么价值。

在这种情况下你可以做两件事

  1. 删除<form>元素。它应该仍然有效地工作
  2. 处理表单提交事件。 对于例如
  3. <form @submit="handleSubmit($event)">

    methods: {
        handleSubmit:(e) =>{
          e.preventDefault();
        }
      }
    
相关问题