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

扶醉桌前 提交于 2020-01-29 03:16:38

问题


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.


回答1:


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




回答2:


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




回答3:


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:


Better to use cookies for saving authorization token, look at this nuxt module

https://github.com/microcipcip/cookie-universal/tree/master/packages/cookie-universal-nuxt

Here sample on vuex store module to set cookie

//call async ajax request to get UUID
const uuidReq = await dispatch('getUUID')

if (uuidReq.hasOwnProperty('meta')) {
  commit('setState', {
    uuid: uuidReq.meta.links.me.meta.id,
    isLogin: true
  })

  // calculate expires
  const expDate = new Date()
  expDate.setTime(expDate.getTime() + (state.accExpKey - 0.3) * 1000)
  const expDate2 = new Date()
  expDate2.setTime(expDate.getTime() + 2592000 * 1000)

  const options = {
    path: '/',
    expires: expDate
  }
  const options2 = {
    path: '/',
    expires: expDate2
  }

  const cookieList = [{
      name: 'g_isLogin',
      value: true,
      opts: options2
    },
    {
      name: 'g_accKey',
      value: state.accKey,
      opts: options
    },
    {
      name: 'g_refKey',
      value: state.refKey,
      opts: options2
    },
    {
      name: 'g_userUUID',
      value: uuidReq.meta.links.me.meta.id,
      opts: options
    }
  ]
  this.$cookies.setAll(cookieList)
}

Here sample implementation on custom Nuxt middleware check existing cookie then inject them into vuex state

export default function({ store, route, redirect, app }) {
  const isLogin = app.$cookies.get('g_isLogin') === 'true'
  const accKey = app.$cookies.get('g_accKey') || ''
  const refKey = app.$cookies.get('g_refKey') || ''
  const userUUID = app.$cookies.get('g_userUUID') || ''

  // console.warn('authenticated isLogin:', isLogin)

  // If the user authenticated
  if (isLogin) {
    store.commit('user/setState', {
      isLogin: isLogin,
      accKey: accKey,
      refKey: refKey,
      uuid: userUUID
    })
  } else {
    return redirect('/?prevURL=' + route.path)
  }
}


来源:https://stackoverflow.com/questions/44126493/i-want-to-use-window-localstorage-in-vuex-in-nuxt-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!