乐趣区

关于vue.js:Nuxt中关于asyncData-数据的管理

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)
退出移动版