javascript - How to receive user information after logging in with vue.js in "Vuexy Admin Dashboard Template"
one text
Solution:
you can simoly write method and call in in created hook.
//ProfileDropDown.vue
<template>
<div class="text-right leading-tight hidden sm:block">
<p class="font-semibold">{{ activeUserInfo.displayName }}</p>
<small>Available</small>
</div>
</template>
<script>
import axios from 'axios';
export default {
data () {
return {
activeUserInfo: null
}
},
methods: {
async getUserInfo () {
try {
const res = await axios.get('auth/me', {
headers: { Authorization: 'Bearer token' }
});
this.activeUserInfo = res.data.user;
} catch (e) {}
}
},
async created() {
await this.getUserInfo();
}
}
</script>
If you want get data with store, you can use axios in state.js
import axios from 'axios';
...
const getUserInfo = () => {
const userInfo = {}
try {
const res = await axios.get('auth/me', {
headers: { Authorization: 'Bearer token' }
});
userInfo = res.data.user;
} catch (e) {}
return userInfo
}
...
And in your ProfileDropDown.vue file you can save your code
But in this case axios didn't work globally. If you want use it. you have to import axios in main.js
file and use
//Create vue object
const http = axios.create({baseUrl: 'your base url'});
//set token for all reqeusts
http.interceptors.request.use(config => {
const token: string | null = localStorage.get('token'); //or use what you want
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
config.headers['Accept'] = 'application/json';
config.headers['Content-Type'] = 'application/json';
return config;
},
error => Promise.reject(error)
);
//Create globa axios object for Vue
Vue.prototype.$axios = http;
After that you don't need to import axios anywhere.
Instead of `axios` use `this.$axios` For ex:
...
const res = await this.$axios.get('auth/me')
this. activeUserInfo = res.data.user;
...
Source