前言:
vue+nuxt.js 项目中,根据IP定位赋值,头部可切换城市,header在layouts下调用,首页根据定位接口返回一些数据。
async asyncData(ctx)()里面调用接口,无法再渲染前传递给header,使用nuxtServerInit,这里就碰到一个自己没有注意的小坑坑。
export const state = () => ({
commonPath: '/beijing'
})
export const mutations = {
COMMON_PATH (state, item) {
state.commonPath = item
},
IS_COMMON_PATH (state, item ) {
state.commonPath = item
}
}
export const actions = {
async nuxtServerInit ({ commit }, { app, route }) {
const commonPath = route.params.city ? `/${route.params.city}` : app.$cookies.get('pinyin') ? `/${app.$cookies.get('pinyin')}` : '/beijing'
await commit('COMMON_PATH', commonPath)
}
}
以上是测试代码,我们使用的模块化vuex,所以这里碰到一个小坑,nuxtServerInit 一定要注意放在index.js。