vue-router 路由的用法(分享页面的重定向、动态设置title)

动态设置页面的title

原理:在路由定义的时候在 meta 里面设置一个 title,然后用路由守卫的钩子事件动态替换页面的title。
代码:

// 定义路由
const route = [
    {path:'/',component:home,meta:{index:0,title:'首页'}},
    {path:'/issue',component:issue,children:[
        {path:'',component:commonIssue,meta:{title:'常见问题'}},
        {path:'/issues/:id',component:issueDetail,name:'idetails',meta:{title:'常见问题'}}
    ]}
]
// 注册路由
Vue.use(VueRouter)
const router = new VueRouter({
    routes:routes
})
//单独设置页面的 title
router.beforeEach((to, from, next) => {   // beforeEach 是 router 的钩子函数,在进入路由前执行
  if (to.meta.title) { // 判断是否有标题
    document.title = to.meta.title;
  }
  next();    // 这个一定不能忘了!不然路由不会跳转的!  
})

分享页面的重定向

之前做微信公众号项目有的这个需求,需要做到只要是用户分享出去的页面,都自动跳转到一个项目介绍页,避免其他用户点进来,因为没有权限访问,而出现页面空白的情况。
原理也是一样,通过 vue-router 的钩子函数,在路由跳转之前,判断一下是否是从分享页面过来的,如果是就重定向到一个通用的分享页面,如果不是,就正常跳转。
如何判断页面是从微信分享来的?微信会给分享的页面自动加上一些参数,其中一个‘from=singlemessage/groupmessage/timeline’,表示从好友对话/群组会话/朋友圈分享过来的,所以判断一下页面的 url 上面是否带有 from 即可。
下面是代码:

const route = [
    {path:'/',name:'',component:home},
    {path:'/',name:'share',component:sharePage},
]

router.beforeEach((to, from, next) => {

  let origin = getQueryString('from');
  if(origin){
    if(to.name=='share'){  // 这个地方是为了防止页面死循环
      next();
      return;
    }
    next('/sharePage');
  }else{
    next();
  }
})


    // 这个函数是获取页面 url 参数的,一般会封装到 utils 里面吧
    function getQueryString(name) { 
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
      var r = window.location.search.substr(1).match(reg); 
      if (r != null) return unescape(r[2]); return null; 
    } 

posted @ 2018-09-14 17:10  下小朋友  阅读(8093)  评论(2编辑  收藏  举报