setup函数的职责
业务逻辑应该都封装成单独的函数,在setup里调用这些函数,以清晰地体现业务执行的流程
<script lang="ts">
import { reactive, toRefs} from 'vue'
import { useRouter } from 'vue-router'
import service from '@/utils/request'
import Toast, {useToastEffect} from '@/components/Toast.vue'
const useLoginEffect = (showToast) => {
const router = useRouter()
const data = reactive(
{
username: '',
password: '',
}
)
const {username, password} = toRefs(data)
const handleLogin = async () => {
if(username.value.replace(/^\s+|\s+$/g, '') === '' || password.value.replace(/^\s+|\s+$/g, '') === '') {
showToast('用户名或密码不能为空')
return
}
try {
const result = await service.post('/user/login', {
username: username.value,
password: password.value
})
if(result.data.verifySuccess === true) {
localStorage.isLogin = true
router.push({name: 'Home'})
} else {
showToast('用户名或密码错误')
}
} catch(e) {
showToast('请求失败')
}
}
return {
username,
password,
handleLogin,
}
}
export default {
components: {
Toast
},
setup(){
const {message,show, showToast} = useToastEffect()
const {username,password,handleLogin,} = useLoginEffect(showToast)
return {
username,
password,
handleLogin,
message,
show
}
}
}
</script>
使用 toRefs 将对象转化为独立的 ref
const data = reactive(
{
username: '',
password: '',
}
)
const {username, password} = toRefs(data)
使用 String.trim() 去除空格
if(username.value.trim() === '' ||
password.value.trim() === '') {
showToast('用户名或密码不能为空')
return
}
使用正则表达式实现 Trim()
if(username.value.replace(/^\s+|\s+$/g, '') === '' ||
password.value.replace(/^\s+|\s+$/g, '') === '') {
showToast('用户名或密码不能为空')
return
}
阻止密码输入框自动填充
设置 autocomplete=”new-password”
<input type="password"
placeholder="请输入密码"
v-model="password"
autocomplete="new-password">