mixin這個函數是非常霸道的,局部使用還好,如果是全局使用,在項目比較大的時候,個人覺得不是很好,在vue2的時候,因為沒有組合式API這一說法,所以mixin對開發人員來說能解決好多事情。但是到了vue3,這種方式已經不推薦使用了,因為我們在vue3中,JS都是在setup里面執行的,這個時候如果我們在外面寫一些公共的JS文件,然后暴露出來,在需要使用到的組件里面按需引入,這種比mixin覺得更好。下面就介紹一下使用組合api的形式實現發送驗證碼的邏輯,來代替vue2.0中的mixin。因本文只討論vue3.0的實現方式,對vue2.0實現的邏輯不在討論。是實現方式比較簡單直接上代碼。
1. 首先在utils文件夾中新建一個 useVerifyCode.js文件,文件的實現過程如下;
import { ref} from 'vue'
import { verifyApi, getShortKeyApi } from '@/api/public.js'
const disabled = ref( false )
const text = ref( '獲取驗證碼' )
//發送驗證碼
const sendCode = () => {
if ( disabled.value ) return
disabled.value = true
let n = 60
text.value = '剩余 ' + n + 's';
const run = setInterval( () => {
n = n - 1
if ( n < 0 ) {
clearInterval( run )
}
text.value = '剩余 ' + n + 's'
if ( text.value < '剩余 ' + 0 + 's' ) {
disabled.value = false
text.value = '重新獲取'
}
}, 1000 )
}
// 發送驗證碼邏輯
export function useSendCode () {
return { text, disabled, sendCode }
}
// 獲取短信驗證碼與key
export function useCmsKeyVerify () {
//接受手機號碼
const getKeyVerify = ( phone ) => {
getShortKeyApi().then( async ( res ) => {
const cmsKey = res.data.key
const data = {
phone: phone,
key: cmsKey,
types: 0
}
await verifyApi( data )
.then( ( res ) => {
sendCode()
console.log(‘發送成功’)
} )
.catch( ( error ) => {
console.log(‘發送失敗’)
} )
} )
}
return { getKeyVerify }
}
這里定義一個發送驗證碼的邏輯,返回了disabled 與text兩個值這兩個值將作為其他組件使用時調用的兩個重要參數。其邏輯是點擊發送的邏輯是點擊”獲取驗證碼“時驗證成功時,將顯示文字更改'剩余 ' + n + 's', 60s完成后文字將變成”重新獲取“倒計時過程中不能重復發送驗證碼;以上就是在組合api中完成發送驗證碼的邏輯;
在組件中如何使用,請看下文。
import { ref, reactive } from 'vue'
import { useSendCode, useCmsKeyVerify } from '@/utils/useVerifyCode.js';
// 這里將獲取組合函數的api retrun text, disabled, sendCode 以及函//數并稱
let { text, disabled, sendCode } = useSendCode()
let { getKeyVerify } = useCmsKeyVerify()
// 獲取vuex存取變量
// 發送驗證碼
const sendVerificationCode = (): void => {
if ( !isSendCode.value || disabled.value ) return false
getKeyVerify( formData.phone )
}
在使用過程中組合api的函數還時特別簡單,只要引入即可,其他的樣式問題,這里將不再展示。以上的代碼是基于vue3.0版本的程序編寫組合api開發。該方法也可進一步優化,需要的可自行修改。