You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vuex的mutations中访问并操作localStorage?

Got it, let's break down how to move your localStorage token handling into a Vuex store step by step—plus fix a small bug in your original code along the way.

First, I noticed a critical issue in your existing localStorage logic: you're using this.access_token as the key when calling setItem, but at that point, this.access_token hasn't been assigned yet. That means you're storing the token under an undefined key, which makes it impossible to retrieve later. We'll use a fixed key like user_access_token instead for persistence.

Step 1: Create Your Vuex Store File

First, create a store/index.js file (if you don't have one already) to define your store with state, mutations, and optional actions/getters:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  // State holds our token value
  state: {
    access_token: null
  },
  // Mutations handle synchronous state updates
  mutations: {
    // Set the token in state AND persist it to localStorage
    SET_ACCESS_TOKEN(state, token) {
      state.access_token = token
      localStorage.setItem('user_access_token', JSON.stringify(token))
    },
    // Initialize token from localStorage when the app loads
    INIT_ACCESS_TOKEN(state) {
      const storedToken = localStorage.getItem('user_access_token')
      if (storedToken) {
        state.access_token = JSON.parse(storedToken)
      }
    }
  },
  // Optional: Actions for async operations (like login API calls)
  actions: {
    handleLoginResponse({ commit }, response) {
      if (response.status === 200) {
        console.log('TOKEN_SET', response)
        commit('SET_ACCESS_TOKEN', response.data.access_token)
      }
    }
  },
  // Optional: Getters for easy access to the token across components
  getters: {
    accessToken: state => state.access_token
  }
})

Step 2: Register the Store in Your App

In main.js, import the store and initialize it, plus trigger the token initialization when the app starts:

import Vue from 'vue'
import App from './App.vue'
import store from './store'

new Vue({
  store,
  // Initialize token from localStorage when the app creates
  created() {
    this.$store.commit('INIT_ACCESS_TOKEN')
  },
  render: h => h(App)
}).$mount('#app')

Step 3: Update Your Component Code

Replace your original localStorage logic with Vuex calls:

For the API Response Handler:

// Replace your existing success block with this
if (response.status === 200) {
  console.log('TOKEN_SET', response)
  // Commit the mutation to update state and localStorage
  this.$store.commit('SET_ACCESS_TOKEN', response.data.access_token)
  
  // If you need the token in your component's local state, pull it from Vuex
  // this.access_token = this.$store.state.access_token
  // OR use the getter if you defined it:
  // this.access_token = this.$store.getters.accessToken
}

For the Mounted Hook:

Since we initialize the token in the app's created hook, your component's mounted can simply pull the token from Vuex (no need to read localStorage directly anymore):

mounted() {
  console.log('GOT_TOKEN')
  this.access_token = this.$store.state.access_token
  // Or use the getter: this.access_token = this.$store.getters.accessToken
}

Optional: Use Actions for Async Work

If you want to keep API logic out of your components, you can dispatch the action instead:

// In your component's login method
async performLogin() {
  try {
    const response = await /* Your API login call here */
    this.$store.dispatch('handleLoginResponse', response)
  } catch (error) {
    // Handle login errors here
  }
}

This setup keeps all token management centralized in Vuex, makes it easier to access the token across components, and fixes the original localStorage key bug.

内容的提问来源于stack exchange,提问作者Aadil Hafesji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:43:22