vuex 使用
应用根目录下如果存在 store
目录,Nuxt.js
将启用 vuex
状态树。定义各状态树时具名导出 state
, mutations
, getters
, actions
即可。
store/user.js
export const state = () => ({
userInfo: {}
})
export const mutations = {
loginSuccess (state, value) {
state.userInfo = value
document.cookie = "token=" + value.token
},
}
export const getters = {
isLogin (state) {
return !!state.token
}
}
export const actions = {}
Vuex 持久化
解决 vuex
刷新数据为空问题
通过在 store
的根模块中定义 nuxtServerInit
方法,Nuxt.js
调用它的时候会将⻚面的上下文对象作为第 2 个参数传给它。当我们想将服务端的一些数据传到客户端时,这个方法非常好用。
// 将cookie转成json对象
function cookieparse (cookie) {
let obj = {}
cookie.replace(/\s/g, '').split(';').forEach(v => {
let [name, val] = v.split('=')
obj[name] = val
})
return obj
}
export const mutations = {
loginSuccess (state, value) {
state.userInfo = value
document.cookie = "token=" + value.token
},
}
export const actions = {
async nuxtServerInit ({commit}, {req, $api}) {
let cookie = req.headers.cookie
let token = cookieparse(cookie).token
try {
let res = await $api.user.getUser(token, {}, {loading: false})
commit('loginSuccess', res.data);
} catch (e) {
console.log(e, '=========');
}
}
}
转载:https://www.cnblogs.com/goloving/p/11373989.html
nuxtServerInit 参数打印
[
{
dispatch: [Function: boundDispatch],
commit: [Function: boundCommit],
getters: {},
state: {
network: true,
userInfo: {},
loading: [Object]
},
rootGetters: {},
rootState: {
network: true,
userInfo: {},
loading: [Object]
}
},
<ref *1> {
isStatic: false,
isDev: true,
isHMR: false,
app: {
head: [Object],
store: [Store],
router: [VueRouter],
nuxt: [Object],
render: [Function: render],
data: [Function: data],
beforeCreate: [Function: beforeCreate],
created: [Function: created],
mounted: [AsyncFunction: mounted],
watch: [Object],
computed: [Object],
methods: [Object],
components: [Object],
context: [Circular *1],
'$config': [Object],
'$axios': [Function],
'$myAxios': [Function],
'$api': [Object],
'$dict': [Object]
},
store: Store {
_committing: false,
_actions: [Object: null prototype],
_actionSubscribers: [],
_mutations: [Object: null prototype],
_wrappedGetters: [Object: null prototype] {},
_modules: [ModuleCollection],
_modulesNamespaceMap: [Object: null prototype],
_subscribers: [],
_watcherVM: [Vue],
_makeLocalGettersCache: [Object: null prototype] {},
dispatch: [Function: boundDispatch],
commit: [Function: boundCommit],
strict: true,
getters: {},
_vm: [Vue],
'$router': [VueRouter],
registerModule: [Function: registerModule],
app: [Object],
'$config': [Object],
'$axios': [Function],
'$myAxios': [Function],
'$api': [Object],
'$dict': [Object]
},
payload: undefined,
error: [Function: bound error],
base: '/',
env: {
VUE_APP_TITLE: 'development',
baseURL: '/api',
VUE_APP_OSS_CONFIG: [Object]
},
req: IncomingMessage {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
socket: [Socket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '/',
method: 'GET',
statusCode: null,
statusMessage: null,
client: [Socket],
_consuming: false,
_dumped: false,
originalUrl: '/',
_parsedUrl: [Url],
_parsedOriginalUrl: [Url],
[Symbol(kCapture)]: false,
[Symbol(RequestTimeout)]: undefined
},
res: ServerResponse {
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Socket],
_header: null,
_keepAliveTimeout: 5000,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
locals: {},
statusCode: 200,
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: null
},
ssrContext: {
req: [IncomingMessage],
res: [ServerResponse],
url: '/',
target: 'server',
spa: undefined,
modern: false,
runtimeConfig: [Object],
_registeredComponents: Set(0) {},
styles: [Getter],
_renderStyles: [Function: renderStyles],
_styles: [Object],
redirected: false,
next: [Function (anonymous)],
beforeRenderFns: [],
nuxt: [Object],
fetchCounters: {},
meta: [Object],
asyncData: {}
},
redirect: [Function (anonymous)],
beforeNuxtRender: [Function (anonymous)],
route: {
name: 'index',
meta: [Array],
path: '/',
hash: '',
query: {},
params: {},
fullPath: '/',
matched: [Array]
},
next: [Function (anonymous)],
_redirected: false,
_errored: false,
params: {},
query: {},
'$config': {
_app: [Object]
},
'$axios': [Function: wrap] {
request: [Function: wrap],
getUri: [Function: wrap],
delete: [Function: wrap],
get: [Function: wrap],
head: [Function: wrap],
options: [Function: wrap],
post: [Function: wrap],
put: [Function: wrap],
patch: [Function: wrap],
defaults: [Object],
interceptors: [Object],
CancelToken: [Function],
isCancel: [Function: isCancel],
setBaseURL: [Function: bound setBaseURL],
setHeader: [Function: bound setHeader],
setToken: [Function: bound setToken],
onRequest: [Function: bound onRequest],
onResponse: [Function: bound onResponse],
onRequestError: [Function: bound onRequestError],
onResponseError: [Function: bound onResponseError],
onError: [Function: bound onError],
create: [Function: bound create],
'$request': [Function: bound ],
'$delete': [Function: bound ],
'$get': [Function: bound ],
'$head': [Function: bound ],
'$options': [Function: bound ],
'$post': [Function: bound ],
'$put': [Function: bound ],
'$patch': [Function: bound ]
},
'$myAxios': [Function: wrap] {
request: [Function: wrap],
getUri: [Function: wrap],
delete: [Function: wrap],
get: [Function: wrap],
head: [Function: wrap],
options: [Function: wrap],
post: [Function: wrap],
put: [Function: wrap],
patch: [Function: wrap],
defaults: [Object],
interceptors: [Object],
CancelToken: [Function],
isCancel: [Function: isCancel],
setBaseURL: [Function: bound setBaseURL],
setHeader: [Function: bound setHeader],
setToken: [Function: bound setToken],
onRequest: [Function: bound onRequest],
onResponse: [Function: bound onResponse],
onRequestError: [Function: bound onRequestError],
onResponseError: [Function: bound onResponseError],
onError: [Function: bound onError],
create: [Function: bound create],
'$request': [Function: bound ],
'$delete': [Function: bound ],
'$get': [Function (anonymous)],
'$head': [Function: bound ],
'$options': [Function: bound ],
'$post': [Function (anonymous)],
'$put': [Function (anonymous)],
'$patch': [Function: bound ]
},
'$api': {
user: [Object],
login: [Object],
homeApi: [Object],
ticketApi: [Object],
trade: [Object],
informationApi: [Object],
noticeApi: [Object],
accApi: [Object]
},
'$dict': {
amountSort: [Array],
dueDaysSort: [Array],
acceptorSort: [Array],
endorseArr: [Array],
flawArr: [Array],
quantityArr: [Array],
ticketNode: [Object],
tradeTrustStatusEnum: [Object],
tradeStatus: [Object]
}
}
]