登录功能实现

新建登录页面

在 src/views/auth 新建 Login.vue 文件,复制贴入以下代码:

src/views/auth/Login.vue

 1 <template>
 2   <div class="row">
 3     <div class="col-md-4 col-md-offset-4 floating-box">
 4       <Message :show.sync="msgShow" :type="msgType" :msg="msg"/>
 5 
 6       <div class="panel panel-default">
 7         <div class="panel-heading">
 8           <h3 class="panel-title">请登录</h3>
 9         </div>
10 
11         <div class="panel-body" data-validator-form>
12           <div class="form-group">
13             <label class="control-label">用户名</label>
14             <input v-model.trim="username" v-validator.required="{ title: '用户名' }" type="text" class="form-control" placeholder="请填写用户名">
15           </div>
16           <div class="form-group">
17             <label class="control-label">密码</label>
18             <input v-model.trim="password" id="password" v-validator.required="{ title: '密码' }" type="password" class="form-control" placeholder="请填写密码">
19           </div>
20           <br>
21           <button @click="login" type="submit" class="btn btn-lg btn-success btn-block">
22             <i class="fa fa-btn fa-sign-in"></i> 登录
23           </button>
24         </div>
25       </div>
26     </div>
27   </div>
28 </template>
29 
30 <script>
31 export default {
32   name: 'Login',
33   data() {
34     return {
35       username: '', // 用户名
36       password: '', // 密码
37       msg: '', // 消息
38       msgType: '', // 消息类型
39       msgShow: false // 是否显示消息,默认不显示
40     }
41   },
42   methods: {
43     login(e) {
44       this.$nextTick(() => {
45         const target = e.target.type === 'submit' ? e.target : e.target.parentElement
46 
47         if (target.canSubmit) {
48           this.submit()
49         }
50       })
51     },
52     submit() {
53       const user = {
54         name: this.username,
55         password: this.password
56       }
57       const localUser = this.$store.state.user
58 
59       if (localUser) {
60         if (localUser.name !== user.name || localUser.password !== user.password) {
61           this.showMsg('用户名或密码不正确')
62         } else {
63           this.$store.dispatch('login')
64         }
65       } else {
66         this.showMsg('不存在该用户')
67       }
68     },
69     showMsg(msg, type = 'warning') {
70       this.msg = msg
71       this.msgType = type
72       this.msgShow = false
73 
74       this.$nextTick(() => {
75         this.msgShow = true
76       })
77     }
78   }
79 }
80 </script>
81 
82 <style scoped>
83 
84 </style>
// 1.验证:填写input中的验证规则:验证时候要在panel-body上写data-validator-form属性
//2.写login时,看是否是提交按钮
原文地址:https://www.cnblogs.com/yangguoe/p/9316950.html