一个 Yii + vue 项目(5)vue路由、yii验证码

版权声明:转载请注明出处,谢谢 https://blog.csdn.net/github_38877986/article/details/77543353

有了一个简单的验证方法,于是需要写一个前端页面,首先在 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 ,里面写的也挺简单的,注释虽然是英文的,但猜也猜得出那些参数是干嘛用的。而前端写的刷新的方法其实就是一个带参请求。

猜你喜欢

转载自blog.csdn.net/github_38877986/article/details/77543353
yii