nuxt implements the way store is used in other js files

  • 2021-09-12 00:22:29
  • OfStack

Preface

In the new js file, you want to use the data in store, for example, token wants to use it in the encapsulated axios and request header, or you can get token through JS interface of app and store it in store.

We all know how to use it in vue.

Code


/*
 * @Description: 
 * @Author: lxc
 * @Date: 2019-07-02 16:14:07
 * @LastEditTime: 2019-08-14 16:08:19
 * @LastEditors: lxc
 */
//  Export  store  The place of 

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import actions from './actions'
import mutations from './mutations'
import getters from './getters'
import canteen from './modules/canteen'
import contact from './modules/contact'
import health from './modules/health'
import scan from './modules/scan'

Vue.use(Vuex)

let store
const initStore = () => {
 return store || (store = new Vuex.Store({
 //  Store public data 
 state,
 //  Asynchronous operations are required through the actions Or pass cimmit Direct operation mutations
 actions,
 //  Synchronous playback of data 
 mutations,
 getters,
 modules: {
  // store  Module ....
 }
 }))
}
export default initStore

How to call in other js files:


import store from '@/store'
const TOKEN = 'testToken'

//  Here is just an example 
function getToken() {
 return isNotEmpty(store().state.token) ? store().state.token : TOKEN
}

I can use it myself. I hope it will be helpful to everyone.

Additional knowledge: How nuxt handles user login state persistence: store processing before nuxtServerInit page rendering

In the vue-cli project, we can use vuex-persistedstate, which can persist the state of vuex, and the page refresh will not be lost. Of course, the principle is localStorage!

Of course, you can also use vue-cookies to save token, so the question comes, how can nuxt project save login status?

Although we can use both of the above methods, But there is a problem, Because there is no window object in created hook (window object is required to obtain cookie and localStorage), for example, when you want to obtain login status, that is, when judging whether there is token, you can only operate in mounted, but this will cause a problem, that is, you still can't know the login status one moment after entering the page, which will have an impact on the experience, and there will be hidden delay in displaying components such as user name.

nuxt is very friendly, it provides fetch hooks, and nuxtServerInit, both of which run on the server side and we can operate store very quickly

1. Use of fetch

If the fetch method is set on the page component, it will be called before each load of the component (either on the server side or before switching to the destination route), and this method needs to be coordinated with the server side personnel


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

2. nuxtServerInit

The state tree file specifies the nuxtServerInit method. When nuxtJs calls it, it will pass the context context object of the page as the second parameter to it for the server to call. Like fetch1, it does not include context. redirect and context. error methods. What parameters can be viewed in the official document?

When we want to send some data from the server to the client, we can save it in the state through this acquisition, and the client will take it out from the state.

nuxtServerInit: First, store token into cookie, so that every request will bring its own cookie, then use the parameters {req, res} in nuxtServerInit to obtain cookie attached to the request, then parse token, and then store it into vuex.

Recommended cookie plug-in cookie-universal-nuxt


<script>
import Vuex from 'vuex'
 
let store = () => new Vuex.Store({
 state: {
 token: ''
 },
 mutations: {
 setToken (state, token) {
  state.token = token
 }
 },
 actions: {
 nuxtServerInit({ commit }, { req }) {
  let cookie = req.headers.cookie;
 
  //  Will cookie Turn into json Object (implement the method yourself) 
  let token = cookieparse(cookie).token;
  commit('setToken', token);
 },
 }
})
 
export default store
</script>

context context object:

属性 类型 可用 描述
app vue根实例 客户端 & 服务端 包含所有插件的根实例。例如:想使用axios,可以通过context.app.$axios获取
isClient Boolean 客户端 & 服务端 是否来自客户端渲染,废弃,请使用process.client
isServer Boolean 客户端 & 服务端 是否来自服务端渲染,废弃,请使用process.server
isStatic Boolean 客户端 & 服务端 是否通过nuxt generate
isDev Boolean 客户端 & 服务端 是否开发模式,在生产坏境的数据缓存中用到
isHMR Boolean 客户端 & 服务端 是否通过模块热替换,仅在客户端以dev模式
route 路由 客户端 & 服务端 路由实例
store vuex数据 客户端 & 服务端 Vuex.sttore实例
env l Object 客户端 & 服务端 nuxt.config.js中的环境变量
params Object 客户端 & 服务端 route.params的别名
query Object 客户端 & 服务端 route.query的别名
req http.Request 服务端 Node.js API的Request对象。如果nuxt以中间件形式使用的话,这个对象就根据你所使用的框架(个人理解为页面)而定。nuxt generate 不可用
res http.Reponse 服务端 Node.js API的Reponse对象。如果nuxt以中间件形式使用的话,这个对象就根据你所使用的框架(个人理解为页面)而定。nuxt generate 不可用
redirect Function 服务端 用于重定向另1个路由,状态码在服务端被使用,默认302 redirect([status,]path[,query])
error Function 客户端 & 服务端 前往错误页面,error(parmas),params包含statusCode和message字段
nuxtState Object 客户端 nuxt状态
beforeNuxtRender(fn) Function 服务端 更新NUXT在客户端呈现的变量,具体了解请看官网

Related articles: