Content source: Pull hook education big front-end high salary training camp

Nuxt.js is a server rendering application framework based on vue.js. More information about Nuxt.js is recommended in the official documentation. Today we are mainly talking about the storage of login status, which is realized by combining cookie and VUex state management. This is a solution I learned recently when I studied the front-end high salary training camp of Pull Education. If there are other solutions, please share them.

Store facilitates sharing between components in an application

  1. Nuxt.js is already integrated with vuex, so using vuex in nuxt.js is very easy. Just create store/index.js in the root directory of your project. Instead of creating a store instance in index.js, you can directly define and export state, mutations, and actions on demand. Nuxt will load and register with the container.
// store/index.js // CookieParser is loaded only for server rendering require('cookieparser') : // To prevent data collisions, state must be defined as a function, Return the data object export const state = () => {return {// Login status of the current user user: null } } export const mutations = { setUser (state, Data) {state.user = data}} export const Actions = {// nuxtServerInit is a special action method that is automatically called during server rendering, Run only when server rendering is enabled Initialize container data, Pass data to the client using nuxtServerInit ({commit}, {req}) {let user = null // If there is a Cookie in the request header if (req.headers. Cookie) {// Use cookieParser to convert the Cookie string to a JavaScript object, Parse (req.headers. Cookie) try {user = json.parse (parsed.user)} catch (err) {// Commit ('setUser', user)}} NO valid cookie found}}Copy the code

2. After successful login, store the user information in the Store

// pages/login/index.vue export default { name: 'LoginIndex', methods: {login() {setTimeOut(()=>{// Timer simulation API request const user = {username: 'Tom', password: '123', token: Use this. Codestore.com MIT ('setUser', user)})}}Copy the code

Cookies are stored for both the front and back ends

3. In order to prevent the loss of page refresh data, user information needs to be persisted and stored. However, local storage cannot be used, because local storage will cause the server to fail to get the login status, so we can store user information in cookies.

// pages/login/index.vue /* * Install js-cookie for convenient operation cookie * NPM I js-cookie */ / Because js-cookie only needs to be used in the client, and the server does not use it, So we can load on demand and only load const Cookie = process.client on the client side? require('js-cookie') : undefined export default { name: 'LoginIndex', methods: { login() { ... Set ('user', data.user)})}}Copy the code