setup函数的职责

业务逻辑应该都封装成单独的函数,在setup里调用这些函数,以清晰地体现业务执行的流程

  1. <script lang="ts">
  2. import { reactive, toRefs} from 'vue'
  3. import { useRouter } from 'vue-router'
  4. import service from '@/utils/request'
  5. import Toast, {useToastEffect} from '@/components/Toast.vue'
  6. const useLoginEffect = (showToast) => {
  7. const router = useRouter()
  8. const data = reactive(
  9. {
  10. username: '',
  11. password: '',
  12. }
  13. )
  14. const {username, password} = toRefs(data)
  15. const handleLogin = async () => {
  16. if(username.value.replace(/^\s+|\s+$/g, '') === '' || password.value.replace(/^\s+|\s+$/g, '') === '') {
  17. showToast('用户名或密码不能为空')
  18. return
  19. }
  20. try {
  21. const result = await service.post('/user/login', {
  22. username: username.value,
  23. password: password.value
  24. })
  25. if(result.data.verifySuccess === true) {
  26. localStorage.isLogin = true
  27. router.push({name: 'Home'})
  28. } else {
  29. showToast('用户名或密码错误')
  30. }
  31. } catch(e) {
  32. showToast('请求失败')
  33. }
  34. }
  35. return {
  36. username,
  37. password,
  38. handleLogin,
  39. }
  40. }
  41. export default {
  42. components: {
  43. Toast
  44. },
  45. setup(){
  46. const {message,show, showToast} = useToastEffect()
  47. const {username,password,handleLogin,} = useLoginEffect(showToast)
  48. return {
  49. username,
  50. password,
  51. handleLogin,
  52. message,
  53. show
  54. }
  55. }
  56. }
  57. </script>

使用 toRefs 将对象转化为独立的 ref

  1. const data = reactive(
  2. {
  3. username: '',
  4. password: '',
  5. }
  6. )
  7. const {username, password} = toRefs(data)

使用 String.trim() 去除空格

  1. if(username.value.trim() === '' ||
  2. password.value.trim() === '') {
  3. showToast('用户名或密码不能为空')
  4. return
  5. }

使用正则表达式实现 Trim()

  1. if(username.value.replace(/^\s+|\s+$/g, '') === '' ||
  2. password.value.replace(/^\s+|\s+$/g, '') === '') {
  3. showToast('用户名或密码不能为空')
  4. return
  5. }

阻止密码输入框自动填充

设置 autocomplete=”new-password”

  1. <input type="password"
  2. placeholder="请输入密码"
  3. v-model="password"
  4. autocomplete="new-password">