咱們在作一個項目,登陸註冊頁面是少不了的,爲了人機校驗,驗證碼也是必須的前端
個人這個項目獲取驗證碼,前端發送一個隨機四位數給後端,後端返回一張圖片,前端渲染就能夠後端
template代碼:api
1 <el-form-item label="" prop="captcha_code"> 2 <el-input 3 v-model="loginForm.captcha_code" 4 placeholder="驗證碼" 5 prefix-icon="lj-icon-yanzhengma" 6 autocomplete="off" 7 autocapitalize="off" 8 spellcheck="false" 9 maxlength="4" 10 @keyup.enter.native="handleLogin" 11 style="float: left; width: 122px;" 12 ></el-input> 13 <div class="captcha_code"> 14 <img src="" ref="code" @click="changeCode"> 15 </div> 16 </el-form-item> 17 <el-button 18 :loading="loading" 19 type="primary" 20 style="width: 100%;" 21 @click="handleLogin" 22 >登陸</el-button>
data數據聲明:dom
1 data() { 2 return { 3 loginForm: { 4 username: "", 5 password: "", 6 captcha_key: "", 7 captcha_code: "" 8 }, 9 } 10 }
mounted數據加載完執行方法:this
1 mounted() { 2 // 獲得驗證碼圖片 3 this.changeCode(); 4 }, spa
methods方法:code
1 getCaptchaKey() { 2 let captchaKey = Math.random() 3 .toString(36) 4 .substring(2); 5 return captchaKey; 6 }, 7 changeCode() { 8 let captcha_key = this.getCaptchaKey(); 9 this.loginForm.captcha_key = captcha_key; 10 this.$refs.code.setAttribute( 11 "src", 12 process.env.VUE_APP_API_URL + 13 "auth/get_captcha?captcha_key=" + 14 captcha_key 15 ); 16 }