1、路由
nuxt按照 pages 文件夹的目录结构自动生成路由
http://localhost:3000/user/reg 相当于 去访问 pages文件夹 下的 user文件夹 下的 reg.vue
vue需在 src/router/index.js 手动配置路由
2、入口页面
nuxt页面入口为 layouts/default.vue vue页面入口为 src/App.vue
3、nuxt 类似 router-view , nuxt-link 类似 router-link
4、webpack配置
nuxt内置webpack,允许根据服务端需求,在 nuxt.config.js 中的build属性自定义构建webpack的配置,覆盖默认配置 vue关于webpack的配置存放在build文件夹下
5、asyncData 里面发送ajax 这个东西跟生命周期这些都是平级的
要理解asyncData方法执行时,其实是在服务端完成的,这个数据是在服务端渲染好了的
6、vuex状态持久化
相信很多人对 vue 中的 vuex 状态持久化已经很熟悉了,使用 vuex-persistedstate 或者 vuex-persist 即可。
这里推荐使用Vue,因为 vuex-persist 基于 ts ,webpack 未经配置打包 ts 有问题,而且在 ie 中存在问题。
vue中使用
import persistedState from 'vuex-persistedstate'
export default new Vuex.Store({
// ...
plugins: [persistedState()]
})
更换 sessionStorage 存储方式:
import persistedState from 'vuex-persistedstate'
export default new Vuex.Store({
// ...
plugins: [
persistedState({ storage: window.sessionStorage })
]
})
使用 cookie 存储:
import persistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'
export default new Vuex.Store({
// ...
plugins: [
persistedState({
storage: {
getItem: key => Cookies.get(key),
setItem: (key, value) => Cookies.set(key, value, { expires: 7 }),
removeItem: key => Cookies.remove(key)
}
})
]
})
Nuxt中使用
因为每次请求都自带 cookies ,所以可以在第一次进入页面的 nuxt 服务端初始化方法 nuxtServerInit 中将 cookies 存到 vuex 状态树中。
由于是服务端获取 cookies ,js-cookie 不再适用,需要使用 cookie-universal-nuxt :
npm install cookie-universal-nuxt
之后在 store/index.js 中:
// 定义行为
const actions = {
// nuxt提供的,每次发送请求都会先调用此方法 ,并且第1个参数store, 该方法的第2个参数是context
nuxtServerInit({commit}, {app}) {
const data = {}
data.accessToken = app.$cookies.get('accessToken')
// 更新 vuex 状态树
commit('UPDATE_ALL_STATE', data)
}
}
这里的 app.$cookies.get 是 cookie-universal-nuxt 给我们提供的在服务端获取 cookies 的方法。
他等价于使用 context 中的 req 对象获取 cookie :req.headers.cookie 之后解析出我们需要的对象值。
那问题来了,既然都有原生 vuex 状态持久化方法了为什么还要用 nuxt 的方法,因为在 created 的时候 window 对象不能使用(包括 cookie 和 loaclStorage),只能在 mounted 使用,于是在页面加载的一瞬间不能加载状态树,导致页面数据反馈变慢,而 nuxt 的策略就可以优化这个问题,十分人性化。