创建 Vuex store,并在其中定义一个用于存储用户名的状态。
- // store.js
- import Vue from 'vue';
- import Vuex from 'vuex';
-
- Vue.use(Vuex);
-
- export default new Vuex.Store({
- state: {
- username: '', // 存储登录用户名的状态
- userid:'',//储存登录用户id
- },
- mutations: {
- setUsername(state, username) {
- state.username = username;
- },
- setUserid(state, userid) {
- state.userid = userid;
- },
- },
- });
-
在登录成功后,将用户名保存到 Vuex store 中。
- // 登录成功后的处理
- this.$store.commit('setUsername', username);
- this.$store.commit('setUserid', userid);
在需要获取登录用户名的组件中,使用计算属性来获取用户名。
- <div>
- <p>Welcome, {{ username }}p>
- div>
-
- <script>
- export default {
- computed: {
- username() {
- return this.$store.state.username;
- },
- userid() {
- return this.$store.state.userid;
- },
- },
- };
- script>
-
1.在登录成功后getUserid是我写的后端接口函数,SetUserId将用户id保存到 localStorage 中。
- getUserid()
- .then(response => {
- // 获取用户ID成功
- const userId = response.data;
- setUserId(userId); // 保存用户id
- })
- .catch(error => {
- // 获取用户ID失败,可能是因为用户未登录
- console.error('获取用户ID失败:', error.response.data);
- // 在这里处理未登录的情况,比如跳转到登录页
- });
在auth.js中
- // 设置用户id到 localStorage 中
- export function setUserId(userId) {
- localStorage.setItem('userid', userId);
- }
- export function getUserId() {
- return localStorage.getItem('userid');
- }
在需要获取登录用户名的组件中,通过读取 localStorage 来获取用户id。
- <div>
-
- div>
-
- <script>
- export default {
- data() {
- return {
-
- userid:'',
- };
- },
- mounted() {
-
- this.user = getUserId('userid');
-
- },
- };
- script>
-