一. 使用prerender-spa-plugin插件預渲染
- vue-cli2.0版本
- 安裝插件
npm install prerender-spa-plugin -S
- 在webpack.prod.config.js 中添加
const PrerenderSPAPlugin =require('prerender-spa-plugin')
const Renderer=PrerenderSPAPlugin.PuppeteerRenderer
//plugins 添加PrerenderSPAPlugin
new PrerenderSPAPlugin({
// 生成文件的路徑,也可以與webpakc打包的一致。
staticDir: path.join(__dirname, '../dist'),
// 對應自己的路由文件
routes: ['/','/news','/about','/contact'],
renderer: new Renderer({
inject: {
foo: 'bar'
},
headless: false,
})
3.修改main.js
new Vue({
el: '#app',
router,
data:{
hasShow:true,
},
render: h => h(App),
mounted () {
document.dispatchEvent(new Event('custom-render-trigger'))
}
})
二. 優(yōu)化配置meta,使用vue-meta-info
- 安裝
npm install vue-meta-info -S
2.main.js引用
import MetaInfo from 'vue-meta-info'
Vue.use(MetaInfo)
- 相應路由頁面配置metaInfo
// about.vue
export default {
metaInfo: {
title: '關于我們',
meta: [{
name: 'keywords',
content: '關于我們'
},
{
name: 'description',
content: '關于我們的頁面'
}
],
},
name: "about",
....
}
- 配置 App.vue
metaInfo(){
return this.metaInfo
},
data(){
return{
metaInfo:{
title:'首頁',
meta: [{
name: 'keywords',
content: '首頁'
},
{
name: 'description',
content: '首頁'
}
],
}
}
},
watch:{
$route(to){
if(to.name==="about"){//根據(jù)不同路由配置不同
this.metaInfo= {
title: '關于我們',
meta: [{
name: 'keywords',
content: '關于我們'
},
{
name: 'description',
content: '關于我們的頁面'
}
],
}
}else{
this.metaInfo={
title:'首頁',
meta: [{
name: 'keywords',
content: '首頁'
},
{
name: 'description',
content: '首頁'
}
],
}
}
}
}