---恢復內容開始---
一、前言
1、簡介預渲染
2、案例演示(不配置預渲染)
3、配置預渲染,
二、主要內容
1、簡介預渲染
SPA有很多優點,但是對搜索引擎SEO不友好,目前主要有兩種方式來解決這個問題: 服務端渲染,預渲染
就像官網所說,如果你只需要改善少數頁面(例如 /
, /about
, /contact
等)的 SEO
,那么你可能需要預渲染。無需使用 web 服務器實時動態編譯 HTML (服務端渲染, SSR),而是使用預渲染方式,在構建時(build time)簡單地生成針對特定路由的靜態 HTML 文件。
2、案例演示
(1)vue-cli構建項目如下
(2)主要文件代碼如下(這里還沒有配置預渲染)

import Vue from 'vue'
import Router from 'vue-router'
//import HelloWorld from '@/components/HelloWorld'
import Home from '@/components/Home'
import About from '@/components/About'
import Test from '@/components/Test'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path:'/about',
name:'About',
component:About
},
{
path:'/test',
name:'Test',
component:Test
}
]
})

<template> <div id='About'> 關於我頁面 </div> </template> <script type="text/javascript"> export default{ name:'About' } </script>

<template> <div> 我是首頁 <router-link to='/Test'></router-link> <router-view/> </div> </template> <script type="text/javascript"> export default{ name:'Home' } </script>

<template> <div>我是測試頁面</div> </template> <script type="text/javascript"> export default{ } </script>
(3)SEO收索引擎在搜索的時候先抓取到的是localhost這個文件,雖然頁面中有內容,但是localhost響應的這個文件中並沒有內容,SEO想獲取內容是獲取不到的,
爬蟲也爬不到這個內容
(4)將項目打包部署在服務器上, 這里一定要用history模式(在index.js文件設置history模式),然后執行npm run build 發現localhost響應的文件里面依然沒有頁面中的內容
3、配置預渲染,
(1)下載插件prerender-spa-plugin
(2)在webpack.prod.config.js里面配置
const PrerenderSPAPlugin = require('prerender-spa-plugin') new PrerenderSPAPlugin({ staticDir: path.join(__dirname, '../dist'),//你要存放的靜態資源目錄 routes: [ '/', '/about']//設置要對哪個文件進行SEO //如果沒有這個配置不會進行預編譯 renderer:new renderer({ inject:{ foo:"far" }, headless:false, //在項目的入口中使用document.dispatchEvent(new Event('render-event')) //這個是你生命的事件名 rendererAfterDocumentEvent:'render-event' })
(3)配置好了之后需要在項目入口文件中觸發這個事件,在main.js中
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>', mounted(){ document.dispatchEvent(new Event('render-event')) } })
(3)npm run build編譯打包,發現編譯出來的dist文件夾下多出一個文件
(4)在dist文件夾下,開一個本地測試服務器hs -o -p 8888,可以看到響應的文件里面有內容了,
(5)如果你的首頁里面還有一個跳轉路由,並且這個路由沒有添加預渲染的話,你刷新下去的話會出現404錯誤
三、參考及總結
https://github.com/chrisvfritz/prerender-spa-plugin
https://cn.vuejs.org/v2/guide/ssr.html
https://juejin.im/post/5b8ba25751882542f25a6cc8
---恢復內容結束---