Nuxt中关于asyncData 数据的管理
需求分析
因为nuxt我们要对其进行seo优化和处理,所以数据基本都要在服务器端渲染完成,也必然都需要塞入到asyncData中,我们针对逐个的axios请求进行处理
代码拆分为 Promise All
async asyncData({ params, store, app, query, error }) {
let getLayout = store.dispatch('layout/getLayout', params.category),
getJobList = store.dispatch('layout/getJobList', Object.assign(query, params));
return new Promise((resolve, reject) => {
return Promise.all([getLayout, getJobList])
.then(() => {
resolve();
})
.catch(err => {
error({ statusCode: 500, message: 'Page exception :' + err });
});
});
},
以上只是一部分,store执行的方法都将进入到vuex中进行管理,我们对其数据进行动态调用
computed: {
...mapState('layout', ['banner', 'content', 'page', 'active', 'pageSize', 'metas', 'menus', 'list'])
}
layout 对应的为store目录,因为我们需要安装功能模块将store进行划分
如图:
export const state = () => ({
locales: ['en', 'zh'],
locale: 'en',
menus: [],
metas: {},
description: '',
active: '',
banner: [],
content: "",
list: [],
page: 0,
pageSize: 10
})
export const mutations = {
setMetas(state, metas) {
state.metas = metas
},
setMenus(state, menus) {
state.menus = menus
},
setActive(state, active) {
state.active = active
},
setField(state, obj) {
const {field, value} = obj
state[field] = value
}
}
export const actions = {
getLayout({commit}, category) {
return new Promise((resolve, reject) => {
this.$request.getFeature({category: category}).then(res => {
let { metas, content, menus, active } = res.data.data
console.log(metas)
commit('setMetas', metas)
commit('setMenus', menus)
commit('setActive', active)
// 首部banner 分离
let banner = content[0]
content = content.slice(1)
commit('setField', {field: 'banner', value: banner})
commit('setField', {field: 'content', value: content})
resolve()
}).catch(err => {
}).finally(() => {
})
return Promise.resolve()
})
},
getJobList({commit}, filter) {
return new Promise((resolve, reject) => {
this.$request.getJobList(filter).then(res => {
let list = res.data.data.list
let { page, pageSize } = res.data.meta
commit('setField', {field: 'list', value: list})
commit('setField', {field: 'page', value: page})
commit('setField', {field: 'pageSize', value: pageSize})
resolve()
}).catch(err => {
reject(err)
})
})
}
}
配置 head
head() {
return {
title: this.metas.title,
meta: [
{ hid: 'description', name: 'description', content: this.metas.description },
{ hid: 'keyword', name: 'keyword', content: this.metas.keyword }
]
};
}![图片描述...](https://cdn.surest.cn/FucM3nAy8Wggx43cD7CrTrJGfmI9)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。