一個 Yii + vue 專案(5)vue路由、yii驗證碼
阿新 • • 發佈:2018-12-26
有了一個簡單的驗證方法,於是需要寫一個前端頁面,首先在 vue src/ 建一個單頁面 login.vue
<template>
<div id="app">
<form>
<div>
<label>賬號:</label>
<input type="text" name="">
</div>
<div>
<label >密碼:</label>
<input type="password" name="">
<div>
<img :src="captcha" @click="refresh">
</div>
</div>
<button>登陸</button>
</form>
</div>
</template >
<script>
import {$get, $post} from './assets/js/public'
export default {
name: 'login',
data: () => { return {
captcha : 'http://yii.com/index.php/home/site/captcha'
}},
methods: {
refresh: function(){
let url = 'http://yii.com/index.php/home/site/captcha?refresh'
$get(url).then((res)=>{
this.captcha = 'http://yii.com/index.php' + res.url
})
}
}
}
</script>
修改 app.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
將login.vue 加入預設路由:
router/default.js
import Vue from 'vue'
import Router from 'vue-router'
import login from '../src/login.vue'
Vue.use(Router)
export default new Router({
routes: [
{path: '/login', name: 'login', component: login },
]
})
開啟頁面看到:
驗證碼沒有出來,所以還要配置一下,這裡解釋一下,yii控制器中以駝峰 action 開頭格式寫的方法稱為動作,動作又分內聯動作和獨立動作,我們之前寫的 actionTest 便是內聯動作,動作id是 test,而驗證碼屬於獨立動作,需要在 actions 方法中註冊下:
在 home/controllers/TestController.php 新增如下方法
public function actions(){
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'width' => 60,
'height' => 40,
'padding' => 0,
'maxLength' => 4,
'minLength' => 4,
]
];
}
實際的執行是 yii\captcha\CaptchaAction 這個類,他一般在 yii vendor/yiisoft/yii2/captcha/CaptchaAction.php 中。
重新整理,可以看到驗證碼:
這裡也建議去看一下 CaptchaAction.php ,裡面寫的也挺簡單的,註釋雖然是英文的,但猜也猜得出那些引數是幹嘛用的。而前端寫的重新整理的方法其實就是一個帶參請求。