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