I want to use window.localStorage in Vuex in Nuxt.

2019-02-07 13:34发布

I developing nuxt.js app. And point is login & logout.


We will develop a login to the JWT system.

You must remain logged in at vuex.

However, when I refresh the page, vuex is initialized.

I've read git vuex-persistedstate , but it's hard to understand just how to initialize and set it.

What is the best way to develop a login system in nuxt.js?

Thanks.

3条回答
聊天终结者
2楼-- · 2019-02-07 13:59

I have used vuex-persist package instead, very easy to get it up and running. This works for SSR too.

import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersist from 'vuex-persist'
import actions from './actions'
import mutations from './mutations'
import getters from './getters'

Vue.use(Vuex)
let vuexLocalStorage = null;

if (process.browser) {

    vuexLocalStorage = new VuexPersist({
      key: 'vuex', // The key to store the state on in the storage provider.
      storage: window.localStorage, // or window.sessionStorage or localForage
    })
}

export function createStore() {
    return new Vuex.Store({
        state: {
        
        },
        actions,
        mutations,
        getters,
        plugins: process.browser ? [vuexLocalStorage.plugin] : []
    })
}

Just make sure to condition everything to just run in the browser

查看更多
▲ chillily
3楼-- · 2019-02-07 14:05

I would strongly recommend using cookies over localStorage with nuxt and the vuex store. Using a package such as univeral-cookie and the built-in nuxtServerInit action, you can populate both client and server stores by reading the cookies on the initial request from the server. You may be limited in the amount of data you can store with cookies but if you implement a RESTful-like API and store ids in your cookies whenever possible, you can server-side fetch that data to populate the full stack store thereby setting yourself up very well in cases where the user refreshes the page. I found it very handy with auth tokens, too, which expire on their own cookie-related behavior and hence wont exist in the store (or its mutation handled decoded data) in cases where the page refreshes.

查看更多
闹够了就滚
4楼-- · 2019-02-07 14:19

Using vuex-persisted state would be the best use case for your scenario.

I will walk you through the process of using vuex-persisted state.

  1. Open command line, cd to your project directory, then enter npm install --save vuex-persistedstate. This will install vuex-persistedstate into your project dependencoes.
  2. Now in your store.js file or wherever your defined your vuex store, add the vuex-persistedstate plugin

    import createPersistedState from 'vuex-persistedstate'
    import * as Cookie from 'js-cookie'
    
    Vue.use(Vuex);
    
    export const store = new Vuex.Store({
        state:{
            user:{
                name: 'john doe',
                age: ' 16'
            },
            loggedIn: false,
            hobbies: ['eating', 'partying']
        },
        plugins: [
             createPersistedState({
                 paths: ['user', 'loggedIn'],
                 getState: (key) => Cookie.getJSON(key), 
                 setState: (key, state) => Cookie.set(key, state, { expires: 1, secure: false })
             })
          ]
    }); 
    
  3. You also need js-cookie package which makes handling cookies easier. Use npm install --save js-cookie.

  4. The paths property says which parts of the state to persist, in our case save as cookies.If no path property is given, then the whole state is persisted
  5. From the above example we have mentioned the paths paths: ['user', 'loggedIn'], so only user and loggedIn properties of the state are saved in cookies not hobbies.
  6. In case you are using modules in your store, the way of defining the pats to persist would be as follows:

    import createPersistedState from 'vuex-persistedstate'
    import * as Cookie from 'js-cookie'
    
    import myModule from './myModule'
    import myAnotherModule from './myAnotherModule'
    
    
    Vue.use(Vuex);
    
    export const store = new Vuex.Store({
        state:{
            user:{
                name: 'john doe',
                age: ' 16'
            },
            loggedIn: false,
            hobbies: ['eating', 'partying']
        },
        modules:{
            myModule,
            myAnotherModule
        },
        plugins: [
             createPersistedState({
                 paths: ['user', 'loggedIn', 'myModule.<nameOfThePropretyInState>'],
                 getState: (key) => Cookie.getJSON(key), 
                 setState: (key, state) => Cookie.set(key, state, { expires: 1, secure: false })
             })
          ]
    }); 
    
  7. In your paths you will refer to the module's property in the state you want to persist. In the above example, the property of the state that you mention of myModule is persisted. myAnotherModule state is not saved since it is not mentioned in the paths.

  8. That's it . If you want to customize the way you use vuex-persisted state and js-cookie, have a look at their documentation.

  9. If you want to check whether your desired state is saved in cookies then you can console log your cookies like this: console.log(document.cookie in your App.vue created() lifecycle hook

查看更多
登录 后发表回答