How to store data to local storage with Nuxt.js

前端 未结 3 2005
忘了有多久
忘了有多久 2021-02-15 15:02

As you know, nuxtjs is server side rendering and there is no good example how to store data into localstorage which is client side.

My work is need to build login form w

相关标签:
3条回答
  • 2021-02-15 15:06

    A little late to the party, but I was having similar problems.

    But first I would recommend you to use cookies for saving a key/token/jwt. The reason being that localStorage can be hijacked through JS api's and cookies can be safeguarded from that. You will however have to safeguard your token from CSFR. That can be done by having a look at the Refence and Origin headers server side. This guy wrote a good post on how to do that: How to protect your HTTP Cookies

    As for accessing localStorage from Nuxt, here we go:

    If you are running Nuxt and haven't told it to run in spa mode it will run in universal mode. Nuxt defines universal mode as:

    Isomorphic application (server-side rendering + client-side navigation)

    The result being that localStorage is not defined serverside and thus throws an error.

    The give away for me was that console logging from middleware files and Vuex outputted to terminal and not the console in developer tools in the browser.

    if you want to read more about my solution you can find it here: localStorage versus Nuxt's modes

    0 讨论(0)
  • 2021-02-15 15:23

    You can use process.browser to check it's in browser or not.

    export default {
      created() {
        this.storeToken();
      },
      methods:{
        storeToken(token){
          if(process.browser){
              localStorage.setItem("authToken", token);
          }
        }
      }
    }

    You also call this method in mounted without check process.browser.

    export default {
      mounted() {
        this.storeToken();
      },
      methods:{
        storeToken(token){
           localStorage.setItem("authToken", token);
        }
      }
    }

    0 讨论(0)
  • 2021-02-15 15:29

    nuxtjs provides you with process.browser to tell it to execute only on the client side

    so use it like this:

    methods:{
        storeToken(token){
            if(process.browser){
                localStorage.setItem("authToken", token);
            }
        }
    }
    

    see this link for more info

    0 讨论(0)
提交回复
热议问题