简体   繁体   中英

vuejs created hook: window/localstorage is not defined

I would like to save authenticated user to localstorage and load them into vuex on the next page load:

created () {
    let user = window.localStorage.getItem('user')
    if(user) {
        this.setUser(JSON.parse(user))
    }
}

I thought that the created hook in my root component would be the right place for this. Unfortunately I get 'window is not defined'.

It works when I put it in the mounted hook instead. Unfortunately this is to late and shows the login page for a few ms.

Where should I put this logic?

I would try first remove window, because you don't need to write that let user = localStorage.getItem('user')

If this is not sufficient just use this vuex plugin https://github.com/robinvdvleuten/vuex-persistedstate it does exactly what you want with zero config. If you want only one value to be persisted you can set this as path in the plugin config.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM