简单封装登录组件,全局注册,利用element-ui库
如图:
定义Login.vue组件
<template> <div> <el-form :model="ruleForm" :rules="rules" ref="ruleForm"> <el-form-item prop="username"> <el-input v-model="ruleForm.username" placeholder="请输入用户名"> <i slot="prefix" class="el-icon-user"></i> </el-input> </el-form-item> <el-form-item prop="password"> <el-input v-model="ruleForm.password" placeholder="请输入密码" show-password > <i slot="prefix" class="el-icon-lock"></i> </el-input> </el-form-item> <el-form-item> <el-button @click="login" type="primary" style="100%" >登录</el-button > </el-form-item> </el-form> </div> </template> <script> export default { name: "Login", components: {}, props: { ruleForm: { type: Object, required: true, }, rules: { type: Object, required: true, }, }, methods: { login() { this.$refs.ruleForm.validate((valid) => { if (valid) { this.$emit('event', 'submit'); }else{ this.$emit('event', 'errHandle') } }); }, }, }; </script>
注册公共组件
在globalComponent中 index.js中
// 注册全局组件
import Vue from "vue"
import Login from "../components/Login.vue"
Vue.component('Login',Login)
在main.js引入注册
import Vue from 'vue'
import App from './App.vue'
import store from './store'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import "./globalComponents"; //引入公共组件index
Vue.config.productionTip = false
Vue.use(ElementUI);
new Vue({
store,
router,
render: h => h(App)
}).$mount('#app')
在view文件中登录页面。
<template> <div> <h1>登录组件</h1> <div> <Login :rule-form="ruleForm" :rules="rules" @submit="submit" @errHandle="errHandle" ></Login> </div> </div> </template> <script> export default { name: "LoginPage", components: {}, props: {}, data() { return { ruleForm: { username: "", password: "", }, rules: { username: [ { required: true, message: "用户名不能为空", trigger: "blur", }, { min: 2, max: 6, message: "用户名在2-6之间", trigger: "blur", }, ], password: [ { required: true, message: "密码不能为空", trigger: "blur", }, { min: 2, max: 6, message: "密码在2-6之间", trigger: "blur", }, ], }, }; }, methods: { submit() { this.$message.success("提交成功"); }, errHandle() { this.$message.error("表单错误"); }, }, }; </script>
至此! 简单的封装就ok了!