注意生成sitemap依赖于@nuxtjs/sitemap,并且需要用axios进行请求,不要使用@nuxtjs/axios,不然会报错
npm install @nuxtjs/sitemap
npm install axios
# 在第一行引入
const axios = require('axios')
# 在modules中添加@nuxtjs/sitemap
modules: [
'@nuxtjs/sitemap'
],
# 在最后面添加
sitemap: {
path: '/sitemap.xml', // sitemap path,不用改
hostname: 'https://www.gaozhe.net/', // sitemap网址的前缀
cacheTime: 60 * 60 * 6, // 更新频率,只在 generate: false有用
gzip: true, // 生成 .xml.gz 压缩的 sitemap
generate: false, // 允许使用 nuxt generate 生成
// 排除不要页面
exclude: [
'/404',
'/page',
'/details',
'/article',
'/tags',
'/category',
'/search'
],
// 页面路由
routes (callback) {
axios.all([
// 文章分类
axios.get('https://api.gaozhe.net/categories/', {
params: {
type: 2
}
}),
// 遍历所有文章
axios.get('https://api.gaozhe.net/posts', {
params: {
type: 2,
page: 1,
per_page: 100,
_embed: true
},
data: { progress: false }
}),
// 文章标签
axios.get('https://api.gaozhe.net/blog', {
params: {
type: 2
}
})
]).then(axios.spread(function (menu, posts, info) {
let now = new Date();
now.setHours(now.getHours(), now.getMinutes() - now.getTimezoneOffset());
let indexRoutes = [
{
url: '/',
changefreq: 'daily',
priority: 1,
lastmodISO: now.toISOString()
}
]
let menuRoutes = menu.data.map((data) => {
let url = ''
if (data.ctype === 1) {
url = '/category/1?type=' + data.id + '&title=' + data.cname
}
if (data.ctype === 2) {
url = '/page/' + data.id
}
return {
url: url,
changefreq: 'monthly',
priority: 0.8,
lastmodISO: data.add_time
}
});
let postsRoutes = posts.data.results.map((data) => {
return {
url: '/details/' + data.id,
changefreq: 'daily',
priority: 0.9,
lastmodISO: data.update_at
}
});
let tagsRoutes = info.data[0].blog_tag.map((data) => {
return {
url: `/tags/1?type=${data.id}&title=${data.tname}`,
changefreq: 'weekly',
priority: 0.7,
lastmodISO: data.add_time
}
})
// 用concat进行数据合并
callback(null, indexRoutes.concat(menuRoutes, postsRoutes, tagsRoutes));
}), function (err) {
throw (err);
});
}
}
在nuxt.config.js的meta中添加网站的字符编码、语言、响应式标签、网站描述、网站关键字等信息;在link中添加全局的css、网站logo等信息。
head: {
title: pkg.name,
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: pkg.description }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
在nuxt.js项目pages路由页面的script中添加head方法,该方法将随nuxt运行时自动载入
head () {
return {
title: `${this.info.blogName} | ${this.info.blogDescription}`,
meta: [
{ name: 'keywords', content: this.info.keywords },
{ name: 'description', content: this.info.description }
]
}
}
在nuxt项目的static文件夹下,配置项目的静态文件,直接在static新建robots.txt即可,nuxt运行时会自动装配到根路由