优秀的编程知识分享平台

网站首页 > 技术文章 正文

vue-admin-template调用action获取用户资料

nanyue 2024-09-29 15:09:21 技术文章 131 ℃

1.vuex的store中定义action

store/modules/user.js

import { getToken, setToken, removeToken } from '@/utils/auth'
            import { login, getUserInfo } from '@/api/user'

            const state = {
        token: getToken(),
                userInfo: {} // 存储用户基本资料用的状态
    }
const mutations = {
        setToken(state, token) {
            state.token = token
            // 同步到缓存
            setToken(token)
        },
        removeToken() {
            // 删除vuex的token
            state.token = null
            removeToken()
        },
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo
        }
    }
const actions = {
        async login(context, data) {
            console.log(data)
            // 调用登陆接口,返回一个token
    const token = await login(data)
            console.log('login-token,', token)
            context.commit('setToken', token.token)

            console.log(state.token)
        },
        async getUserInfo(context) {
        // 将该结果保存到vuex上,还要提前设置状态
        // 状态有了之后,那么还必须通过mutations修改状态
    const result = await getUserInfo()
        context.commit('setUserInfo', result)
  }

    }

    export default {
        namespaced: true, // 开启命名空间
                state,
                mutations,
                actions
    }

2.主页中调用该action

views/dashboard/index.vue

    <template>
  <div class="dashboard-container">
    <div class="dashboard-text">name: {{ name }}</div>
    <svg-icon icon-class="dashboard" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

    export default {
        name: 'Dashboard',
                computed: {
    ...mapGetters([
                    'name'
                    ])
        },
        created() {
            // 初始化执行
            this.$store.dispatch('user/getUserInfo')
        }

    }
</script>

<style lang="scss" scoped>
            .dashboard {
  &-container {
            margin: 30px;
        }
  &-text {
            font-size: 30px;
            line-height: 46px;
        }
    }
</style>

3.api/user.js中访问封装的接口

import request from '@/utils/request'

    export function login(data) {
        return request({
                url: '/employee/login',
                method: 'post',
                data
  })
    }

    export function getUserInfo() {
        return request({
                url: '/sys/profile',
                method: 'get'
  })
    }

Tags:

最近发表
标签列表