前言:众所周知,Vue SPA单页面应用对SEO不友好,固然也有相应的解决方案,下面列出几种最近研究和使用过的SEO方案,SRR和静态化基于Nuxt来讲。css
1.SSR服务器渲染;
2.静态化;
3.预渲染prerender-spa-plugin;
4.使用Phantomjs针对爬虫作处理。html
1.SSR服务器渲染前端
关于服务器渲染:Vue官网介绍 ,对Vue版本有要求,对服务器也有必定要求,须要支持nodejs环境。vue
使用SSR权衡之处:node
优点:ios
不足:(开发中遇到的坑)nginx
1.一套代码两套执行环境,会引发各类问题,好比服务端没有window、document对象,处理方式是增长判断,若是是客户端才执行:git
1
2
3
|
if
(process.browser){
console.log(window);
}
|
引用npm包,带有dom操做的,例如: wowjs ,不能用 import 的方式,改用:github
1
2
3
4
|
if
(process.browser) {
var
{ WOW } = require(
'wowjs'
);
require(
'wowjs/css/libs/animate.css'
);
}
|
2.Nuxt asyncData方法,初始化页面前先获得数据,但仅限于 页面组件 调用:web
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// 并发加载多个接口:
async asyncData ({ app, query }) {
let [resA, resB, resC] = await Promise.all([
app.$axios.get(
'/api/a'
),
app.$axios.get(
'/api/b'
),
app.$axios.get(
'/api/c'
),
])
return
{
dataA: resA.data,
dataB: resB.data,
dataC: resC.data,
}
}
|
在asyncData中获取参数:
1.获取动态路由参数,如:
/list/:id' ==> '/list/123
接收:
1
2
3
|
async asyncData ({ app, query }) {
console.log(app.context.params.id)
//123
}
|
2.获取url?获取参数,如:
/list?id=123
接收:
1
2
3
|
async asyncData ({ app, query }) {
console.log(query.id)
//123
}
|
3.若是你使用 v-if 语法,部署到线上大概也会遇到这个错误:
Error while initializing app DOMException: Failed to execute 'appendChild' on 'Node': This node type does not support this method.
at Object.We [as appendChild]
根据github nuxt上的 issue第1552条 提示,要将 v-if 改成 v-show 语法。
4.坑太多,留坑,晚点更。
2.静态化
在 Nuxt.js 执行 generate 静态化打包时,动态路由会被忽略。
1
2
3
4
|
-| pages/
---| index.vue
---| users/
-----| _id.vue
|
须要动态路由先生成静态页面,你须要指定动态路由参数的值,并配置到 routes 数组中去。
1
2
3
4
5
6
7
8
9
10
|
// nuxt.config.js
module.exports = {
generate: {
routes: [
'/users/1'
,
'/users/2'
,
'/users/3'
]
}
}
|
运行打包,便可看见打包出来的页面。
可是若是路由动态参数的值是动态的而不是固定的,应该怎么作呢?
使用一个返回 Promise 对象类型 的 函数;
使用一个回调是 callback(err, params) 的 函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
// nuxt.config.js
import axios from
'axios'
export
default
{
generate: {
routes:
function
() {
.then((res) => {
return
res.data.map((user) => {
return
{
route:
'/users/'
+ user.id,
payload: user
}
})
})
}
}
}
|
如今咱们能够从 /users/_id.vue 访问的 payload ,以下所示:
1
2
3
4
|
async asyncData ({ params, error, payload }) {
if
(payload)
return
{ user: payload }
else
return
{ user: await backend.fetchUser(params.id) }
}
|
若是你的动态路由的参数不少,例如商品详情,可能高达几千几万个。须要一个接口返回全部id,而后打包时遍历id,打包到本地,若是某个商品修改了或者下架了,又要从新打包,数量多的状况下打包也是很是慢的,很是不现实。
优点:
不足:
3.预渲染prerender-spa-plugin
若是你只是用来改善少数营销页面(例如 /, /about, /contact 等)的 SEO,那么你可能须要预渲染。无需使用 web 服务器实时动态编译 HTML,而是使用预渲染方式,在构建时 (build time) 简单地生成针对特定路由的静态 HTML 文件。优势是设置预渲染更简单,并能够将你的前端做为一个彻底静态的站点。
1
|
$ cnpm
install
prerender-spa-plugin --save
|
vue cli 3 vue.config.js 配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
const PrerenderSPAPlugin = require(
'prerender-spa-plugin'
);
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;
const path = require(
'path'
);
module.exports = {
configureWebpack: config => {
if
(process.env.NODE_ENV !==
'production'
)
return
;
return
{
plugins: [
new
PrerenderSPAPlugin({
// 生成文件的路径,也能够与webpakc打包的一致。
// 下面这句话很是重要!!!
// 这个目录只能有一级,若是目录层次大于一级,在生成的时候不会有任何错误提示,在预渲染的时候只会卡着不动。
staticDir: path.join(__dirname,
'dist'
),
// 对应本身的路由文件,好比a有参数,就须要写成 /a/param1。
routes: [
'/'
,
'/product'
,
'/about'
],
// 这个很重要,若是没有配置这段,也不会进行预编译
renderer:
new
Renderer({
inject: {
foo:
'bar'
},
headless:
false
,
// 在 main.js 中 document.dispatchEvent(new Event('render-event')),二者的事件名称要对应上。
renderAfterDocumentEvent:
'render-event'
})
}),
],
};
}
}
|
在main.js中添加:
1
2
3
4
5
6
7
|
new
Vue({
router,
render: h => h(App),
mounted () {
document.dispatchEvent(
new
Event(
'render-event'
))
}
}).$mount(
'#app'
)
|
注意:router中必须设置 mode: “history” 。
打包出来能够看见文件,打包出文件夹 /index.html ,例如: about => about/index.html ,里面有html内容。
优点:
不足:
4.使用Phantomjs针对爬虫作处理
Phantomjs是一个基于webkit内核的无头浏览器,即没有UI界面,即它就是一个浏览器,只是其内的点击、翻页等人为相关操做须要程序设计实现。
虽然“PhantomJS宣布终止开发”,可是已经知足对Vue的SEO处理。
这种解决方案实际上是一种旁路机制,原理就是经过Nginx配置, 判断访问的来源UA是不是爬虫访问,若是是则将搜索引擎的爬虫请求转发到一个node server,再经过PhantomJS来解析完整的HTML,返回给爬虫。
具体代码戳这里: vue-seo-phantomjs 。
要安装全局 phantomjs ,局部 express ,测试:
1
|
$ phantomjs spider.js
'https://www.baidu.com'
|
若是见到在命令行里出现了一推html,那恭喜你,你已经征服PhantomJS啦。
启动以后或者用postman在请求头增长 User-Agent 值为 Baiduspider ,效果同样的。
部署上线
线上要安装 node
、 pm2
、 phantomjs
,nginx相关配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
upstream spider_server {
server localhost:3000;
}
server {
listen 80;
server_name example.com;
location / {
proxy_set_header Host $host:$proxy_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
if
($http_user_agent ~*
"Baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator|bingbot|Sosospider|Sogou Pic Spider|Googlebot|360Spider"
) {
proxy_pass http:
//spider_server
;
}
}
}
|
优点:
不足:
总结
若是构建大型网站,如商城类,别犹豫,直接上SSR服务器渲染,固然也有相应的坑等你,社区较成熟,英文好点,一切问题都迎刃而解。
若是只是我的博客、公司官网这类,其他三种均可以。
若是对已用SPA开发完成的项目进行SEO优化,并且支持node服务器,请使用 Phantomjs 。
不多写文章,这是我这个月对Vue SEO方案的探索,写的不对的地方请指出,谢谢理解~
以上就是本文的所有内容,但愿对你们的学习有所帮助,也但愿你们多多支持脚本之家。