nuxt的head动态填充数据进行SEO
2021-07-27 17:00:33
先官方在nuxt.config.js中nuxt提供了一个head属性的用法,这里是一个全局的默认head属性
head: { title: 'cmsfront', htmlAttrs: { lang: 'en' }, meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' }, { hid: 'description', name: 'description', content: '' }, { name: 'format-detection', content: 'telephone=no' } ], link: [ { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' } ] },
当我们需要通过后端返回的数据动态展示我们需要的meta信息来方便seo时,我们就需要在页面里添加一个head属性,(hid作为唯一标识保持一致)
回到我们业务上,每一页都有自己的头部信息,我们就需要在逻辑页添加head(){}信息。
//栏目首页 category.vue head({params}) { const thisCatArr = this.homeCategory.filter(item=>item.cateFolder===params.catname) const thisCat = thisCatArr[0] return { title: thisCat.catName, meta: [{ hid: "description", name: "description", content: thisCat.description }] } },
在 head 方法里可通过 this 关键字来获取组件的数据,这样你可以利用页面组件的数据来设置个性化的 meta 标签。附带一句,我们可以解构this, 直接获取当前页的有用数据;
但是我们正常调用接口都是在mounted里面调用然后发现页面数据是显示出来了,但是我们要的meta信息还是undefined,因为mounted不适合nuxt的服务端渲染 ,这时候就要说一下nuxt提供的asyncData钩子,asyncData可以获取上下文信息,用一个栏目首页为例
head({params}) { const thisCatArr = this.homeCategory.filter(item=>item.cateFolder===params.catname) const thisCat = thisCatArr[0] return { title: thisCat.catName, meta: [{ hid: "description", name: "description", content: thisCat.description }] } }, async asyncData({ params }: Context) { const homeCategory = await asyncAxios('category', { siteid: params.siteid }) console.log(homeCategory) return { homeCategory } },
这样我们再查看源码时 我们的meta信息就都显示出来了