前言
首先,Vue3的Hooks是一种新的 API,用于在Vue组件中管理状态和生命周期。它们是基于 React Hooks的概念设计的,可以让开发者更方便地在函数式组件中使用状态管理和生命周期函数。本文给大家分享一下基于Hooks实现的两个案例。
一、示例代码
(1)/src/views/HelloWorld.vue
<template>
<div class="index">
<h1>{
{ code }}</h1>
<p>
<el-input size="small" style="font-size: 13px" placeholder="请输入验证码" />
<el-button size="small" :disabled="isDisabled" @click="sendCode">{
{ countdownText }}</el-button>
</p>
<p>{
{ `disabled=${isDisabled}` }}</p>
</div>
</template>
<script lang='ts' setup>
import {
useRandomCode } from '@/hooks/useRandomCode'
const code = useRandomCode()
import useCountDown from '@/hooks/useCountDown'
const {
countdownText, isDisabled, sendCode } = useCountDown(60)
</script>
<style lang="less" scoped>
.index {
position: relative;
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
overflow: hidden;
justify-content: center;
align-items: center;
p {
display: flex;
flex-direction: row;
align-items: center;
}
}
</style>
(2)/src/hooks/useRandomCode.js
import {
ref, onMounted, onBeforeUnmount, onUnmounted } from 'vue'
/**
* 4位随机数
*/
export const useRandomCode = () => {
const code = ref(('000' + Math.floor(Math.random() * 10000)).slice(-4))
const fn = () => {
let num = Math.floor(Math.random() * 10000)
num = ('000' + num).slice(-4)
return num
}
setInterval(() => {
code.value = fn()
}, 1000)
onMounted(() => {
console.log('useRandomCode -> onMounted')
})
onBeforeUnmount(() => {
console.log('useRandomCode -> onBeforeUnmount')
})
onUnmounted(() => {
console.log('useRandomCode -> onUnmounted')
})
return code
}
(3)/src/hooks/useCountDown.ts
import {
ref, Ref, onMounted, onBeforeUnmount, onUnmounted } from 'vue'
/**
* 60秒倒计时
*/
export default (num: number, text = '发送验证码'): ({
countdownText: Ref<string>, isDisabled: Ref<boolean>, sendCode: () => void }) => {
const countdownNum = ref(num)
const countdownText = ref(text)
const isDisabled = ref(false)
const sendCode = () => {
countdownText.value = `${
countdownNum.value}s`
isDisabled.value = true
const timer = setInterval(() => {
countdownNum.value--
countdownText.value = `${
countdownNum.value}s`
if (countdownNum.value === 0) {
clearInterval(timer)
countdownNum.value = num
countdownText.value = text
isDisabled.value = false
}
}, 1000)
}
onMounted(() => {
console.log('useCountDown -> onMounted')
})
onBeforeUnmount(() => {
console.log('useCountDown -> onBeforeUnmount')
})
onUnmounted(() => {
console.log('useCountDown -> onUnmounted')
})
return {
countdownText, isDisabled, sendCode }
}