【问题标题】:localStorage in Nuxt js is not working in SSR modeNuxt js 中的 localStorage 在 SSR 模式下不起作用
【发布时间】:2021-07-12 03:34:14
【问题描述】:

我正在尝试使用 vuex 在购物车中添加商品,但在控制台中出现了一些错误,并且页面中的产品也没有显示。请告诉我如何解决这个问题。 这是控制台中的错误

client.js?06a0:103 SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at Store.initializeStore (index.js?9101:14)
    at wrappedMutationHandler (vuex.esm.js?2f62:844)
    at commitIterator (vuex.esm.js?2f62:466)
    at Array.forEach (<anonymous>)
    at eval (vuex.esm.js?2f62:465)
    at Store._withCommit (vuex.esm.js?2f62:624)
    at Store.commit (vuex.esm.js?2f62:464)
    at Store.boundCommit [as commit] (vuex.esm.js?2f62:409)
    at VueComponent.mounted (default.vue?ec86:82)

这是我尝试使用 localStorage 的 store.js

export const state = () => ({
    cart:{
        items:[],
    },
    isAuthenticated: false,
    token: '',
    isLoading: false,

})
  
export const mutations = {
    initializeStore(state) {
        if (localStorage.getItem('cart')) {
          state.cart = JSON.parse(localStorage.getItem('cart'))
        } else {
          localStorage.setItem('cart', JSON.stringify(state.cart))
        }
    },
    addToCart(state, item) {
        const exists = state.cart.items.filter(i => i.product.id === item.product.id)
        if (exists.length) {
          exists[0].quantity = parseInt(exists[0].quantity) + parseInt(item.quantity)
        } else {
          state.cart.items.push(item)
        }
        localStorage.setItem('cart', JSON.stringify(state.cart))
    },

}

export const actions = {

}

这是我试图从 vuex 访问 localStorage 的 default.vue

export default {
  data(){
    return{
      title:'QL Gadgets',
      cart:{
        items:[]
      },
    }
  },
  mounted(){
    this.$store.commit('initializeStore')
  },
  computed:{
    cartTotalLenght(){
      let totalLenght = 0
      for(let i=0; i < this.cart.items.length; i++){
        totalLenght += this.cart.items[i].quantity
      }
      return totalLenght
    }
  },
  methods:{
    handleClick(){
        if(this.$refs.menu.classList.contains('hidden')){
            this.$refs.menu.classList.remove('hidden')
        }
        else{
            this.$refs.menu.classList.add('hidden')
        }
    }
  },
}

【问题讨论】:

    标签: javascript vue.js nuxt.js vuex


    【解决方案1】:

    服务器无法查看浏览器本地存储,因为本地存储是客户端的一项功能。我认为正在发生的事情是 localStorage.getItem('cart') 正在返回 undefined ,而您看到的错误是在期望找到有效 JSON 时尝试 JSON.parse undefined 。

    由于在服务器渲染期间您的模板中挂载了钩子,您的商店正在触发适用的服务器端功能。

    您将需要等待在客户端调用 localStorage.getItem,然后将其传递回服务器(如果在加载后需要额外的节点访问,则使用 server-miidleware 进行处理)或者只是在客户端处理它并提交要存储的结果。

    我还发现,使用 vuex-persistedstate 可以很好地增强这种逻辑或替代方案,您可以在第一次提交后选择性地保留您的购物车,然后您的服务器可以在以后的应用实例化时访问它。

    【讨论】:

    • mounted() 钩子不在服务器端运行。
    【解决方案2】:

    这里的问题很可能是您在本地存储中设置了一个不可 JSON 解析的字符串,或者响应中没有任何内容(undefinedu 开头)。使用您选择的浏览器(例如 ChromeFirefox)检查您的本地存储,看看是否是这种情况。

    无论如何,您应该处理从本地存储读取或解析结果的错误。例如,用户第一次访问该页面时不会出现任何内容,JSON.parse 将失败。例如:

    export const mutations = {
      initializeStore(state) {
        try {
          state.cart = JSON.parse(localStorage.getItem('cart'))
        } catch {
          localStorage.setItem('cart', JSON.stringify(state.cart))
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-04
      • 2021-07-03
      • 2022-11-07
      • 2021-05-22
      • 1970-01-01
      • 2020-04-18
      • 2019-03-19
      • 2018-02-14
      相关资源
      最近更新 更多