# 1 13.登录功能完善

> 前面代码啰嗦重复，这里我们把之前的代码优化一下

* #### 更新vuex管理

```js
import { createStore } from 'vuex'
import { login,getinfo } from '~/api/manager'
import { setToken } from '~/composables/auth'

// 创建一个新的 store 实例
const store = createStore({
    state() {
        return {
            // 用户信息
            user: {}
        }
    },
    mutations: {
        // 记录用户信息
        SET_USERINFO(state, user) {
            state.user = user
        }
    },
    actions: {
        // 登录
        login({ commit }, {username, password}){
            return new Promise((resolve, reject) => {
                login(username, password).then(res=>{
                    setToken(res.token)

                    resolve(res)
                }).catch(err=>reject(err))
            })
        },

        // 获取当前登录用户信息
        getinfo({ commit }){
            return new Promise((resolve, reject) => {
                getinfo().then(res=>{
                    commit('SET_USERINFO', res)
                    resolve(res)
                }).catch(err=>reject(err))
            })
        }
    }
})


export default store

```

* #### 更新全局前置守卫

```js
import store from '~/store'


// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  
    ...略
    // 如果用户登录了，自动获取用户信息，并存储再 vuex 当中
    if(token){
        await store.dispatch("getinfo")
    }

    next()
  })
```

* #### 更新login.vue

```js
<script setup>
import { ref, reactive, onMounted,onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { toast } from '~/composables/util'
import store from '~/store'

const router = useRouter()

// do not use same name with ref
const form = reactive({
  username: '',
  password: '',
  
})

// 定义验证规则
const rules = {
    username: [
        {
            required: true,
            message: '用户名不能为空',
            trigger: 'blur',
        },
    ],
    password: [
        {
            required: true,
            message: '密码不能为空',
            trigger: 'blur',
        },
    ]
}

// 点击登录验证
const formRef = ref(null)
const loading = ref(false)

const onSubmit = () => {
    formRef.value.validate((valid) => {
        if (!valid) {
            console.log('error')
        }
        // 加载按钮动画
        loading.value = true

        store.dispatch('login', form).then(res=>{
            toast('登录成功')
            router.push('/')

        }).finally(()=> {
            loading.value = false
        })
    })
}

// 坚挺回车事件
function onKeyUp(e){
    // console.log(e)
    if(e.key == 'Enter') onSubmit();
}

// 添加键盘添加
onMounted(()=>{
    document.addEventListener('keyup', onKeyUp)
})

// 移除键盘监听
onBeforeUnmount(()=>{
    document.removeEventListener('keyup', onKeyUp)
})
</script>
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://close.gitbook.io/yun-wei-bi-ji/centos/vue/xiang-mu/1-13.-deng-lu-gong-neng-wan-shan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
