引入Element
1、首先进入项目目录下,用npm
安装Element
npm i element-ui -S
2、在目录src/element/
下创建文件index.js
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
3、然后在main.js
中添加以下代码进行引入
import './element'
至此就完成了element的引入,后面就可以直接在代码中使用element组件。
整体布局
4、对App.vue
进行修改
<template>
<el-container>
<el-header class="header" height="100px">
<h3>我的网站</h3>
<p>VUE小模块之用户登录功能</p>
</el-header>
<el-main>
<router-view></router-view>
</el-main>
</el-container>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
.header {
background-color: #409EFF;
color: white;
}
</style>
修改后效果如下
美化表单
5、对登录页面Login.vue
进行修改
<template>
<el-row type="flex" justify="center">
<el-form :model="user" label-width="80px">
<el-form-item label="用户名">
<el-input v-model="user.name"></el-input>
</el-form-item>
<el-form-item label="密码">
<el-input v-model="user.pass"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="el-icon-upload" @click="login">登录</el-button>
</el-form-item>
</el-form>
</el-row>
</template>
<script>
export default {
methods: {
login () {
this.$router.replace('/')
}
},
data () {
return {
user: {}
}
}
}
</script>
美化后效果如下
表单验证
6、首先配置验证规则
<script>
export default {
methods: {
login () {
this.$router.replace('/')
}
},
data () {
return {
user: {},
rules: {
name: [
{required: true, message: '用户名不能为空', trigger: 'blur'}
],
pass: [
{required: true, message: '密码不能为空', trigger: 'blur'}
]
}
}
}
}
</script>
7、接下来在el-form
标签添加rules
属性绑定为之前配置的验证规则,添加status-icon
属性可显示状态图标
<el-form :model="user" :rules="rules" status-icon label-width="80px">
...
</el-form>
8、除此之外,必须在要实现验证功能的el-form-item
标签中添加prop
属性
<el-form-item label="用户名" prop="name">
...
</el-form-item>
<el-form-item label="密码" prop="pass">
...
</el-form-item>
9、效果如图所示
但是此时仍然可以提交表单
提交表单
10、首先为el-form
元素增加ref
属性以便login
方法进行调用
<el-form ref="loginForm" :model="user" :rules="rules" status-icon label-width="80px">
...
</el-form>
11、接下来修改login
方法
login () {
this.$refs.loginForm.validate((valid) => {
if (valid) {
this.$router.replace('/')
} else {
return false
}
})
}
此时就会对提交表单进行验证了
12、再对表单数据进行验证,只有用户名和密码正确的情况下才进行切换(目前暂时指定用户名和密码,之后连接数据库后再进行远程验证),且验证成功或失败都有提示信息。
login () {
this.$refs.loginForm.validate((valid) => {
if (valid) {
if (this.user.name === 'admin' && this.user.pass === '123456') {
this.$notify({
type: 'success',
message: '欢迎您,' + this.user.name + '!',
duration: 3000
})
this.$router.replace('/')
} else {
this.$message({
type: 'error',
message: '用户名或密码错误',
showClose: true
})
}
} else {
return false
}
})
}
登录失败:
登录成功:
13、此时输入的密码是明文,给密码输入框增加类型type="password"
,此时密码变成密文
<el-input v-model="user.pass" type="password"></el-input>