store front page rendering process nuxtServerInit: How nuxt handle user logged persistence

  vue-cli project, we can use vuex-persistedstate , it can make the state vuex persistence , refresh the page are not lost , of course, is the principle localStorage it ! Of course, you can use vue-cookies to save token , the question is, nuxt project how to save login state? Of course, the above two methods we can use, but there is a problem , since created there is no hook in window objects (acquired cookie, localStorage need window objects), when you need to determine whether there is a token , you have to be in mounted operation , indicating that the page came in a moment you can not know whether or not already logged in , this will lead to display the user name, to show hidden components are belated

  nuxt very friendly, it provides fetch hook , there nuxtServerInit , these two hooks are executed on the server and we can very quickly be operated store

1, FETCH use

  If the page components set fetch method, which will be called (on the server or switch to the target before routing) in front of each component is loaded, this method need to meet with staff end of service

<script>
export default {
  async fetch ({ app, store, params }) {
    let { data } = app.$axios.get('/token');
    store.commit('setToken', data.token);
  }
}
</script>

2, nuxtServerInit

  State tree file specified nuxtServerInit method, Nuxtjs will call it when the context of the page context object as the second argument to call it for the server, and fetch the same, and does not include context.redirect context.error method, What specific parameters can check out the official documentation. When we want to spread to some of the data server client, you can get stored in this state, the client and then take from the state in

  Method Ultimate Invincible nuxtServerInit: first stored token cookie, so that every request comes cookie, then the parameters in use nuxtServerInit {req, res}, to obtain a cookie that came with the request, and then parse the token, and then stored again vuex.

Vuex Import from  ' vuex ' 

the let Store = () => new new Vuex.Store ({ 
  State: { 
    token: '' 
  }, 
  mutations: { 
    setToken (State, token) { 
       state.token = token 
    } 
  }, 
  Actions: { 
    nuxtServerInit (the commit {}, {REQ}) { the let cookie
       = req.headers.cookie ; 

      // the cookie converted into json object (own implementation of the method) 
      the let token = cookieparse (cookie) .token ; 
      the commit ( ' setToken ' , token ); 
    }, 
  }
})

export default store

 

Guess you like

Origin www.cnblogs.com/goloving/p/11373989.html