
目前正在学习 nuxtjs 前端开发,目前遇到一个场景, 如果客户端 cookie 中携带 token,那么页面在 server side 就把用户信息渲染好. 代码如下:
store/index.js
export const state = () => ({ user: null, token: null }); export const mutatiOns= { saveUser(state, userValue) { console.log("这里执行 store.user.save = " + JSON.stringify(userValue)); state.user = userValue; }, saveToken(state, token) { console.log("这里执行 store.token.save = " + token); state.token = token; } }; export const actiOns= { nuxtServerInit({ commit }, app) { const token = app.$cookies.get("token") && app.$cookies.get("token").indexOf("Bearer ") == 0 ? app.$cookies.get("token") : null; console.log('nuxtserver init 初始化 token = ', token) if (token) { commit("saveToken", app.$cookies.get("token")); this.$axios.post("/api/me").then(res => { commit("saveUser", res.data.data); }); } } }; pages/index.vue
<template> <div>{{user}}</div> </template> <script> export default { computed: { user() { console.log("这里执行 computed " + this.$store.state.token) return this.$store.state.user; }, }, } </script> <style> </style> 后台输出
nuxtserver init 初始化 token = Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI0OWYxMjgwZTkxODRjZmMyIiwiZXhwIjoxNjA1NTE2OTAyfQ.ozioLM26fGVO8SfqfZllwp8j6Gy_PWoDsntPzlvXor0 14:25:53 这里执行 store.token.save = Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI0OWYxMjgwZTkxODRjZmMyIiwiZXhwIjoxNjA1NTE2OTAyfQ.ozioLM26fGVO8SfqfZllwp8j6Gy_PWoDsntPzlvXor0 14:25:53 Making request to /api/me 14:25:53 这里执行 computed null 14:25:53 这里执行 store.user.save = {"id":"49f1280e9184cfc2","nickname":"test","avatar":"https://vip1.loli.net/2020/11/15/Eqlr5T7JcmOuDWk.jpg"} 14:25:53 为啥在 index.vue 的 computed 里面 this.$store.state.user 会比 nuxtServerInit commit("saveUser", res.data.data)想执行啊?
为什么会出现这个问题,以及怎么解决
1 lxzxl Nov 16, 2020 你的 nuxtServerInit 没有返回 Promise, 改成 `return this.$axios.post...` |