vuex 使用

应用根目录下如果存在 store 目录,Nuxt.js 将启用 vuex 状态树。定义各状态树时具名导出 state, mutations, getters, actions 即可。

store/user.js

  1. export const state = () => ({
  2. userInfo: {}
  3. })
  4. export const mutations = {
  5. loginSuccess (state, value) {
  6. state.userInfo = value
  7. document.cookie = "token=" + value.token
  8. },
  9. }
  10. export const getters = {
  11. isLogin (state) {
  12. return !!state.token
  13. }
  14. }
  15. export const actions = {}

Vuex 持久化

解决 vuex 刷新数据为空问题

通过在 store 的根模块中定义 nuxtServerInit 方法,Nuxt.js 调用它的时候会将⻚面的上下文对象作为第 2 个参数传给它。当我们想将服务端的一些数据传到客户端时,这个方法非常好用。

  1. // 将cookie转成json对象
  2. function cookieparse (cookie) {
  3. let obj = {}
  4. cookie.replace(/\s/g, '').split(';').forEach(v => {
  5. let [name, val] = v.split('=')
  6. obj[name] = val
  7. })
  8. return obj
  9. }
  10. export const mutations = {
  11. loginSuccess (state, value) {
  12. state.userInfo = value
  13. document.cookie = "token=" + value.token
  14. },
  15. }
  16. export const actions = {
  17. async nuxtServerInit ({commit}, {req, $api}) {
  18. let cookie = req.headers.cookie
  19. let token = cookieparse(cookie).token
  20. try {
  21. let res = await $api.user.getUser(token, {}, {loading: false})
  22. commit('loginSuccess', res.data);
  23. } catch (e) {
  24. console.log(e, '=========');
  25. }
  26. }
  27. }

转载:https://www.cnblogs.com/goloving/p/11373989.html

nuxtServerInit 参数打印

  1. [
  2. {
  3. dispatch: [Function: boundDispatch],
  4. commit: [Function: boundCommit],
  5. getters: {},
  6. state: {
  7. network: true,
  8. userInfo: {},
  9. loading: [Object]
  10. },
  11. rootGetters: {},
  12. rootState: {
  13. network: true,
  14. userInfo: {},
  15. loading: [Object]
  16. }
  17. },
  18. <ref *1> {
  19. isStatic: false,
  20. isDev: true,
  21. isHMR: false,
  22. app: {
  23. head: [Object],
  24. store: [Store],
  25. router: [VueRouter],
  26. nuxt: [Object],
  27. render: [Function: render],
  28. data: [Function: data],
  29. beforeCreate: [Function: beforeCreate],
  30. created: [Function: created],
  31. mounted: [AsyncFunction: mounted],
  32. watch: [Object],
  33. computed: [Object],
  34. methods: [Object],
  35. components: [Object],
  36. context: [Circular *1],
  37. '$config': [Object],
  38. '$axios': [Function],
  39. '$myAxios': [Function],
  40. '$api': [Object],
  41. '$dict': [Object]
  42. },
  43. store: Store {
  44. _committing: false,
  45. _actions: [Object: null prototype],
  46. _actionSubscribers: [],
  47. _mutations: [Object: null prototype],
  48. _wrappedGetters: [Object: null prototype] {},
  49. _modules: [ModuleCollection],
  50. _modulesNamespaceMap: [Object: null prototype],
  51. _subscribers: [],
  52. _watcherVM: [Vue],
  53. _makeLocalGettersCache: [Object: null prototype] {},
  54. dispatch: [Function: boundDispatch],
  55. commit: [Function: boundCommit],
  56. strict: true,
  57. getters: {},
  58. _vm: [Vue],
  59. '$router': [VueRouter],
  60. registerModule: [Function: registerModule],
  61. app: [Object],
  62. '$config': [Object],
  63. '$axios': [Function],
  64. '$myAxios': [Function],
  65. '$api': [Object],
  66. '$dict': [Object]
  67. },
  68. payload: undefined,
  69. error: [Function: bound error],
  70. base: '/',
  71. env: {
  72. VUE_APP_TITLE: 'development',
  73. baseURL: '/api',
  74. VUE_APP_OSS_CONFIG: [Object]
  75. },
  76. req: IncomingMessage {
  77. _readableState: [ReadableState],
  78. _events: [Object: null prototype],
  79. _eventsCount: 1,
  80. _maxListeners: undefined,
  81. socket: [Socket],
  82. httpVersionMajor: 1,
  83. httpVersionMinor: 1,
  84. httpVersion: '1.1',
  85. complete: true,
  86. headers: [Object],
  87. rawHeaders: [Array],
  88. trailers: {},
  89. rawTrailers: [],
  90. aborted: false,
  91. upgrade: false,
  92. url: '/',
  93. method: 'GET',
  94. statusCode: null,
  95. statusMessage: null,
  96. client: [Socket],
  97. _consuming: false,
  98. _dumped: false,
  99. originalUrl: '/',
  100. _parsedUrl: [Url],
  101. _parsedOriginalUrl: [Url],
  102. [Symbol(kCapture)]: false,
  103. [Symbol(RequestTimeout)]: undefined
  104. },
  105. res: ServerResponse {
  106. _events: [Object: null prototype],
  107. _eventsCount: 1,
  108. _maxListeners: undefined,
  109. outputData: [],
  110. outputSize: 0,
  111. writable: true,
  112. destroyed: false,
  113. _last: false,
  114. chunkedEncoding: false,
  115. shouldKeepAlive: true,
  116. _defaultKeepAlive: true,
  117. useChunkedEncodingByDefault: true,
  118. sendDate: true,
  119. _removedConnection: false,
  120. _removedContLen: false,
  121. _removedTE: false,
  122. _contentLength: null,
  123. _hasBody: true,
  124. _trailer: '',
  125. finished: false,
  126. _headerSent: false,
  127. socket: [Socket],
  128. _header: null,
  129. _keepAliveTimeout: 5000,
  130. _onPendingData: [Function: bound updateOutgoingData],
  131. _sent100: false,
  132. _expect_continue: false,
  133. locals: {},
  134. statusCode: 200,
  135. [Symbol(kCapture)]: false,
  136. [Symbol(kNeedDrain)]: false,
  137. [Symbol(corked)]: 0,
  138. [Symbol(kOutHeaders)]: null
  139. },
  140. ssrContext: {
  141. req: [IncomingMessage],
  142. res: [ServerResponse],
  143. url: '/',
  144. target: 'server',
  145. spa: undefined,
  146. modern: false,
  147. runtimeConfig: [Object],
  148. _registeredComponents: Set(0) {},
  149. styles: [Getter],
  150. _renderStyles: [Function: renderStyles],
  151. _styles: [Object],
  152. redirected: false,
  153. next: [Function (anonymous)],
  154. beforeRenderFns: [],
  155. nuxt: [Object],
  156. fetchCounters: {},
  157. meta: [Object],
  158. asyncData: {}
  159. },
  160. redirect: [Function (anonymous)],
  161. beforeNuxtRender: [Function (anonymous)],
  162. route: {
  163. name: 'index',
  164. meta: [Array],
  165. path: '/',
  166. hash: '',
  167. query: {},
  168. params: {},
  169. fullPath: '/',
  170. matched: [Array]
  171. },
  172. next: [Function (anonymous)],
  173. _redirected: false,
  174. _errored: false,
  175. params: {},
  176. query: {},
  177. '$config': {
  178. _app: [Object]
  179. },
  180. '$axios': [Function: wrap] {
  181. request: [Function: wrap],
  182. getUri: [Function: wrap],
  183. delete: [Function: wrap],
  184. get: [Function: wrap],
  185. head: [Function: wrap],
  186. options: [Function: wrap],
  187. post: [Function: wrap],
  188. put: [Function: wrap],
  189. patch: [Function: wrap],
  190. defaults: [Object],
  191. interceptors: [Object],
  192. CancelToken: [Function],
  193. isCancel: [Function: isCancel],
  194. setBaseURL: [Function: bound setBaseURL],
  195. setHeader: [Function: bound setHeader],
  196. setToken: [Function: bound setToken],
  197. onRequest: [Function: bound onRequest],
  198. onResponse: [Function: bound onResponse],
  199. onRequestError: [Function: bound onRequestError],
  200. onResponseError: [Function: bound onResponseError],
  201. onError: [Function: bound onError],
  202. create: [Function: bound create],
  203. '$request': [Function: bound ],
  204. '$delete': [Function: bound ],
  205. '$get': [Function: bound ],
  206. '$head': [Function: bound ],
  207. '$options': [Function: bound ],
  208. '$post': [Function: bound ],
  209. '$put': [Function: bound ],
  210. '$patch': [Function: bound ]
  211. },
  212. '$myAxios': [Function: wrap] {
  213. request: [Function: wrap],
  214. getUri: [Function: wrap],
  215. delete: [Function: wrap],
  216. get: [Function: wrap],
  217. head: [Function: wrap],
  218. options: [Function: wrap],
  219. post: [Function: wrap],
  220. put: [Function: wrap],
  221. patch: [Function: wrap],
  222. defaults: [Object],
  223. interceptors: [Object],
  224. CancelToken: [Function],
  225. isCancel: [Function: isCancel],
  226. setBaseURL: [Function: bound setBaseURL],
  227. setHeader: [Function: bound setHeader],
  228. setToken: [Function: bound setToken],
  229. onRequest: [Function: bound onRequest],
  230. onResponse: [Function: bound onResponse],
  231. onRequestError: [Function: bound onRequestError],
  232. onResponseError: [Function: bound onResponseError],
  233. onError: [Function: bound onError],
  234. create: [Function: bound create],
  235. '$request': [Function: bound ],
  236. '$delete': [Function: bound ],
  237. '$get': [Function (anonymous)],
  238. '$head': [Function: bound ],
  239. '$options': [Function: bound ],
  240. '$post': [Function (anonymous)],
  241. '$put': [Function (anonymous)],
  242. '$patch': [Function: bound ]
  243. },
  244. '$api': {
  245. user: [Object],
  246. login: [Object],
  247. homeApi: [Object],
  248. ticketApi: [Object],
  249. trade: [Object],
  250. informationApi: [Object],
  251. noticeApi: [Object],
  252. accApi: [Object]
  253. },
  254. '$dict': {
  255. amountSort: [Array],
  256. dueDaysSort: [Array],
  257. acceptorSort: [Array],
  258. endorseArr: [Array],
  259. flawArr: [Array],
  260. quantityArr: [Array],
  261. ticketNode: [Object],
  262. tradeTrustStatusEnum: [Object],
  263. tradeStatus: [Object]
  264. }
  265. }
  266. ]