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; 
    } 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM