Node.js/nuxt/生命周期:修订间差异
来自康健生活
| 第86行: | 第86行: | ||
* head | * head | ||
* render | * render | ||
== question == | |||
=== store === | |||
在实际项目中,由于在 nuxt 的一些存储在 store 中的数据,比如验证登陆状态的 token 等,只能在 mounted 中操作(直到 mounted 周期才挂载 window 对象),这样又会引发一个问题,在进入页面的瞬间无法立即获得 token(包括一系列的开销),视觉上会有明显的延迟感。 | |||
如果使用 nuxt,可以借助 fetch 和 nuxtServerInit 规避这个问题,在页面渲染(组件加载 )前快速操作 store。 | |||
==== fetch ==== | |||
<syntaxhighlight lang="javascript"> | |||
export default { | |||
async fetch({ app, store, params}) { | |||
let { data } = app.$axios.get(/token) | |||
store.commit('user/setToken', data.token) | |||
} | |||
}</syntaxhighlight> | |||
==== nuxtServerInit ==== | |||
<syntaxhighlight lang="javascript"> | |||
let store = () => new Vuex.store({ | |||
state: { | |||
token: '' | |||
}, | |||
mutations: { | |||
setToken (state, token) { | |||
state.token = token | |||
} | |||
}, | |||
actions: { | |||
nuxtServerInit({ commit}, { req }) { | |||
let cookie = req.headers.cookie | |||
commit('setToken ', cookie.token) | |||
} | |||
} | |||
})</syntaxhighlight> | |||