先晒下版本 PS D:\vue\vueJS-001\dist> vue -V @vue/cli 4.1.2
一个好网站,没有优秀的 title 以及 keywords\Keyword 就不行,在 vue cli4 中如何定义这些呢,这里分享两个方法。
进入 router 文件夹底下的 index.js 文件
首先引入:
import Vue from 'vue' import Router from 'vue-router'
然后在路由里面配置每个路由的地址:
routes: [ { /* (首页)默认路由地址 */ path: '/', name: 'Entrance', component: Entrance, meta: { title: '首页入口' } }, { /* 修改昵称 */ path: '/modifyName/:nickName', name: 'modifyName', component: modifyName, meta: { title: '修改昵称' } }, { /* 商品详情 */ path: '/goodsDetail', name: 'goodsDetail', component: goodsDetail, meta: { title: '商品详情' } }, { /* Not Found 路由,必须是最后一个路由 */ path: '*', component: NotFound, meta: { title: '找不到页面' } } ]
在每一个 meta 里面设置页面的 title 名字,最后在遍历
router.beforeEach((to, from, next) => { /* 路由发生变化修改页面 title */ if (to.meta.title) { document.title = to.meta.title } next() })
这样就为每一个 VUE 的页面添加了 title
#方法二 使用 vue-meta 进行 mate 动态管理 HTML head 信息 vue-meta 的官方文档在这里 https://github.com/declandewet/vue-meta 文档中比较详细地说明了在浏览器端和服务器端如何使用 vue-meta 修改页面头部信息,这里我主要介绍下在 SPA 项目中管理 meta info 的使用方法。,
vue 单页运用中,对单独页面使用 meta 的时候,他不是直接修改,而是插在下面覆盖上面的 meta 进行修改。 1、安装 npm install vue-meta --save
2、在 main.js 引入
import Meta from 'vue-meta' Vue.use(Meta)
3、为需要修改的页面单独定义 metaInfo
export default { metaInfo: { title: 'This is the test', meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=2,user-scalable=yes' } ] } }
4、异步请求数据可以使用
如果 component 中使用了异步请求数据,可以使用 metaInfo() 方法。
<template> <div> <h1>{{{ title }}}</h1> </div> </template> <script> export default { name: 'post', data () { return { title: '' description: '这是一篇文章...' } }, metaInfo () { return { title: this.title, meta: [ { vmid: 'description', name: 'description', content: this.description } ] } }, created () { this.initData() }, methods: { initData () { axios.get('some/url').then((resp) => { // 设置 title 时 metaInfo 会同时更新 this.title = resp.title this.description = resp.decription }) } } } </script>
再看一个实例:
export default { name: 'DealRepair', metaInfo: { title: 'This is the test', meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no' } ] }, data () { return { } }, mounted(){ }, methods:{ } }
第三个实例,附与其它数据并存:
<template> <div> <div class="container"> <ul class="list-unstyled"> <li v-for="node in nodes" :key="node.NodeID"><a href="Javascript:;" @click="navTo(node)">{{node.NodeName}}</a></li> </ul> </div> </div> </template> <script> export default{ data:function(){ var model={nodes:[]}; var pid=this.$route.params.id; window.console.log(pid); this.jsp("node_list",{"pid":pid}).then((ret)=>{ model.nodes=JSON.parse(ret.result); }) return model; }, metaInfo: { title: '节点列表', meta: [ { description: '自动逻辑的列表' }, { keywords: '节点,列表,栏目' }, ] }, methods:{ navTo:function(node){ this.$router.push("/NodeContent/"+node.NodeID); } }, } </script> <style> </style>