#laravel #vue.js
Вопрос:
Уважаемые профессора, я легко вхожу в систему с настройками axios. Но после входа в систему у меня возникли проблемы с получением информации о пользователе из базы данных.
Я использую автономную сеть и xampp. И я использую этот шаблон. Панель администратора Vuexy
// axios
import axios from 'axios'
// for connect to zampp server
const baseURL = 'http://127.0.0.1:8000'
export default axios.create({
baseURL,
headers:{
common:{
'Access-Control-Allow-Origin' : '*'
}
}
})
И я использую этот код для входа в систему:
//jwt.js
login (email, pwd) {
return axios.post('/api/auth/login', {
email,
password: pwd
})
},
refreshToken () {
return axios.post('/api/auth/refresh-token', {accessToken: localStorage.getItem('accessToKen')})
}
Конечно, используя этот код.
//LoginJWT.vue
loginJWT () {
// if (!this.checkLogin()) return
// Loading
this.$vs.loading()
const payload = {
checkbox_remember_me: this.checkbox_remember_me,
userDetails: {
email: this.email,
password: this.password
}
}
this.$store.dispatch('auth/loginJWT', payload)
.then(() => { this.$vs.loading.close() })
.catch(error => {
this.$vs.loading.close()
this.$vs.notify({
title: 'Error',
text: error.message,
iconPack: 'feather',
icon: 'icon-alert-circle',
color: 'danger'
})
})
},
Используя следующий код, мы считываем имя пользователя из поддельной базы данных.
activeUserInfo.Имя дисплея
//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>
export default {
data () {
return {
}
},
computed: {
activeUserInfo () {
return this.$store.state.AppActiveUser
}
},
methods: {
}
}
</script>
Наконец, отсюда возвращается поддельное имя пользователя.
Отображаемое имя: «Мэри Адамс»,
//state.js
/*=========================================================================================
File Name: state.js
Description: Vuex Store - state
----------------------------------------------------------------------------------------
Item Name: Vuexy - Vuejs, HTML amp; Laravel Admin Dashboard Template
Author: Pixinvent
Author URL: http://www.themeforest.net/user/pixinvent
==========================================================================================*/
import navbarSearchAndPinList from '@/layouts/components/navbar/navbarSearchAndPinList'
import themeConfig, { colors } from '@/../themeConfig.js'
// /////////////////////////////////////////////
// Helper
// /////////////////////////////////////////////
// *From Auth - Data will be received from auth provider
const userDefaults = {
uid : 0, // From Auth
displayName : "Mary Adams", // From Auth
about : 'Dessert chocolate cake lemon drops jujubes. Biscuit cupcake ice cream bear claw brownie brownie marshmallow.',
photoURL : require('@assets/images/portrait/small/avatar-s-11.jpg'), // From Auth
status : 'online',
userRole : 'admin'
}
const getters = {
// get_user : response.data.userInfo
}
const userInfoLocalStorage = JSON.parse(localStorage.getItem('userInfo')) || {}
// Set default values for active-user
// More data can be added by auth provider or other plugins/packages
const getUserInfo = () => {
const userInfo = {}
// Update property in user
Object.keys(userDefaults).forEach((key) => {
// If property is defined in localStorage => Use that
userInfo[key] = userInfoLocalStorage[key] ? userInfoLocalStorage[key] : userDefaults[key]
})
// Include properties from localStorage
Object.keys(userInfoLocalStorage).forEach((key) => {
if (userInfo[key] === undefined amp;amp; userInfoLocalStorage[key] !== null) userInfo[key] = userInfoLocalStorage[key]
})
return userInfo
}
// Check if device is touch device
// This is used to remove perfect scrollbar from touch devices
// Using Dynamic components
const is_touch_device = () => {
const prefixes = ' -webkit- -moz- -o- -ms- '.split(' ')
const mq = function (query) {
return window.matchMedia(query).matches
}
if ('ontouchstart' in window || window.DocumentTouch) {
return true
}
// include the 'heartz' as a way to have a non matching MQ to help terminate the join
// https://git.io/vznFH
const query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join('')
return mq(query)
}
// /////////////////////////////////////////////
// State
// /////////////////////////////////////////////
const state = {
AppActiveUser : getUserInfo(),
bodyOverlay : false,
isVerticalNavMenuActive : true,
is_touch_device : is_touch_device(),
mainLayoutType : themeConfig.mainLayoutType || 'vertical',
navbarSearchAndPinList,
reduceButton : themeConfig.sidebarCollapsed,
verticalNavMenuWidth : 'default',
verticalNavMenuItemsMin : false,
scrollY : 0,
starredPages : navbarSearchAndPinList['pages'].data.filter((page) => page.is_bookmarked),
theme : themeConfig.theme || 'light',
themePrimaryColor : colors.primary,
// Can be used to get current window with
// Note: Above breakpoint state is for internal use of sidebar amp; navbar component
windowWidth: null
}
export default state
Теперь я хочу помочь вам, как я могу считывать информацию из базы данных mysql.
Обратите внимание, что я так легко вхожу в систему. Но после входа в систему я не знаю, как получить информацию о пользователе. Извините, я новичок 🙁 Пожалуйста, помогите мне
Комментарии:
1. Я знаю, что мои вопросы для начинающих, но у меня была эта проблема в течение нескольких месяцев. Пожалуйста, приведите мне реальный пример. Или, если у вас есть ссылка на ответ, пришлите ее мне. спасибо всем