1. 程式人生 > >vue-element-admin原始碼分析(一)

vue-element-admin原始碼分析(一)

這兩天看花褲衩大大的手摸手系列,使用vue+element+vuex+axios實現了一個後臺模板(專案地址),在閱讀原始碼的過程中收益匪淺,以下做一些筆記。(由於是學習大大專案的思想,所以略去了很多大大的程式碼)。 這裡只是做一個登陸頁面,然後能提交資料給後臺並能接收資料,暫時沒有做路由守衛同跳轉。

首先配置並安裝好好所需要的main.js

import Vue from 'vue'
import App from './App'
import router from './router'     //路由
import './assets/styles/reset.css'//初始化css樣式
Vue.config.productionTip = false
import Element from 'element-ui'  //引入element-ui
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(Element)
import store from '@/store/index'  //vuex
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

配置路由router/index.js

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
  routes: [
    {
	    path: '/',
	    component: () => import('@/views/login/index'),
	    hidden: true
	},
  ]
})

登陸頁面:views/login/index.vue

1、這裡自定義校驗規則,在el-form裡定義:rules並傳入約定的驗證規則,並將 Form-Item 的 prop 屬性設定為需校驗的欄位名,然後在data裡宣告規則,這裡定義表單都是必須填寫,當滑鼠失去焦點,即滑鼠點了其他地方會觸發,校驗器為自定義行數,自定義函式最後呼叫callback()。如:

data(){
	const validateUsername = (rule,value,callback)=>{..some code... callback();}
	const validatePassword= (rule,value,callback)=>{..some code... callback();}//自定義校驗規則,傳入3個引數value表示要校驗的資料。
	return {
		loginRules:{
					username: [{required:true,trigger:'blur',validator:validateUsername}],//這裡表示必填表單,失去焦點時觸發,檢驗器為:validateUsername
					password: [{required:true,trigger:'blur',validator:validatePassword}]
				},
	}
}

2、當點選按鈕是做兩個工作,一是判斷表單是否已經完成校驗,二是傳送請求。這裡為了方便儲存並呼叫使用者資訊,使用vuex管理使用者狀態,使用this.$store.dispatch(這裡現在main.js配置好store)方法傳給vuex的actions。

在methods裡通過 this.$refs.loginForm.validate(valid=>{})校驗表單是否驗證正確,若 驗證正確valid=true,若驗證失敗valid=false 程式碼如下:

<template>
	<div class="login-container">
		<el-form :model="loginForm" :rules="loginRules" ref="loginForm" class="login-form" auto-complate="on">
			<div class="title-container">
				<h3 class="title">後臺登入</h3>
			</div>
			<el-form-item prop="username">
				 <el-input
		          v-model="loginForm.username"
		          placeholder="使用者名稱"
		          name="username"
		          type="text"
		          auto-complete="on"
		        />
			</el-form-item>
			<el-form-item prop="password">
				 <el-input
		          v-model="loginForm.password"
		          placeholder="密碼"
		          name="password"
		          type="text"
		          auto-complete="on"
		        />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登入</el-button>
			</el-form-item>
		</el-form>
	</div>

</template>
<script>
	export default {
		data(){
			const validateUsername = (rule,value,callback) => {
				const usernamemap = ['admin','editor'];
				if(!usernamemap.indexOf(value.trim()) >= 0){
					callback(new Error ('please input the correct username'))
				}else{
					callback()
				}
			}
			const validatePassword = (rule,value,callback) => {
				if(value.length<6){
					callback(new Error ('The password can not be less then 6 digits'))
				}else{
					callback()
				}
			}
			return {
				loginForm:{
					username:'admin',
					password:'111111'
				},
				loginRules:{
					username: [{required:true,trigger:'blur',validator:validateUsername}],
					password: [{required:true,trigger:'blur',validator:validatePassword}]
				},
				loading:false,
			}
		},
		methods:{
			handleLogin(){
				this.$refs.loginForm.validate(valid => {
					if(valid){//檢驗通過
						this.loading=true;
						//this.$store.dispatch('LoginByUsername',this.loginForm)
						this.$store.dispatch('LoginByUsername',this.loginForm).then(()=>{this.loading=false;console.log('success')}).catch(()=>{console.log('err')})
					}
				})
			}
		},
	}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;
	.login-container{
		position:fixed;
		width:100%;
		height:100%;
		background-color:$bg;
		.login-form{
			position:absolute;
			left:0;
			right:0;
			width:520px;
			max-width:100%;
			margin:120px auto;
		}
	}
	.title-container{
		postion:relative;
		.title{
			font-size:26px;
			color:$light_gray;
			margin: 0px auto 40px auto;
			text-align:center;
			font-weight:bold;
		}
	}
</style>

傳輸資料與儲存資料

請求攔截器的封裝 這裡使用axios傳送與接受請求,為了做許可權認證這裡在每次傳送請求header都會攜帶上一個X-Token,所以封裝了一個axios的攔截器。設定傳送請求的字首為http://localhost/vue/(這是我自己定義的) utils/request.js

import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: 'http://localhost/vue/', // api 的 base_url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    if (store.getters.token) {
      // 讓每個請求攜帶token-- ['X-Token']為自定義key 請根據實際情況自行修改
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => response,

  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

傳送請求 api/login.js 使用php的同學需要用qs.stringify對傳輸的資料轉換一下格式。這裡的loginByUsername返回的是一個axios例項,方便後邊vuex進行then或catch操作

import request from '@/utils/request' //引入攔截器
import axios from 'axios'
import qs from 'qs'
export function loginByUsername(username, password) {
  const data = {
    username,
    password
  }
  return request({
    url: 'login.php',
    method: 'post',
    data:qs.stringify(data)   //這裡對資料進行了轉換(原文是沒有轉換的,但我用的是php)
  })
}

login.php 該檔案與先專案存在同源策略問題,故需要配置一下header,讓非同源請求可以請求並受到相應的資料,注意需要設定可以X-Token。為了做出一個效果,這裡隨便簡單地寫一個邏輯。

<?php
<?php
header('Access-Control-Allow-Origin:*');  // 響應型別 
header('Access-Control-Allow-Methods:*');   // 響應頭設定 
header('Access-Control-Allow-Headers:x-requested-with,content-type,X-Token');   //設定可以接受X-Token頭
if(isset($_POST['username'])&&isset($_POST['password'])){
	if($_POST['username']=='admin'&&$_POST['password']=='111111'){
		$res['login'] = md5(true);
	}else{
		$res['login'] = md5(false);
	}
	//$res['login'] = true;
	echo json_encode($res);	
}

?>

Vuex 這裡的actions.LoginByUsername返回一個Promise物件,方便login頁面作進一步then或catch操作

import Vue from 'vue'
import Vuex from 'vuex'
import { loginByUsername } from '@/api/login'
import { setToken,getToken } from '@/utils/auth'
Vue.use(Vuex);

const store = new Vuex.Store({
	state:{
		token:getToken() || ''
	},
	mutations:{
		LoginByUsername(state,data){
			state.token = setToken(data.login)
		}
	},
	actions:{
		LoginByUsername(ctx,userInfo){
			return new Promise((resolve,reject)=>{
				loginByUsername(userInfo.username, userInfo.password).then(response=>{
					ctx.commit('LoginByUsername',response.data);
					resolve();
				}).catch(error => {reject(error)})
			})
			
		}
	}
})

export default store

總結: 執行流程: login頁面進行表單驗證,然後驗證成功點選按鈕,將資料傳送到vuex,有actions的方法傳送請求LoginByUsername,傳送請求時會進行一個請求攔截,會在請求頭header里加入X-Token,php返回token以及其他資料如許可權等並存儲在vuex和cookie,LoginByUsername會返回一個Promise物件,方便login頁面呼叫then或catch操作。