vue之導航路由+路徑傳參
阿新 • • 發佈:2019-02-05
1、搭好路由後在path路徑傳參一個2,
tag="span"可改變<a>標籤為<span>,
另外可通過.router-link-active給標籤設定導航樣式
.router-link-active{
color: red;
}
如下:
<router-link to="/home/2" tag="span">首頁</router-link> <router-link to="/about" tag="span">關於</router-link> <router-link to="/other" tag="span">其他</router-link>
2、在需要接收的路由配置規則裡,對應的路徑後面新增 :id
// 配置路由規則
var routes=[
{path:'/home/:id',component:Home},
{path:'/about',component:About},
{path:'/other',component:Other}
]
3、在Home配置模板通過 this.$route.params 可接收 id:2 的值this指向模板的$route
注意:只適合傳單個數據 ,不適合多個數據
<template id="home"> <div> <h2>首頁--</h2> <p>{{this.$route.params.id }}</p> 值為2 this指向模板的$route </div> </template>
var Home={
template:"#home",
mounted(){
console.log(this.$route.params)
}
}
4、
完整程式碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="vue.js" type="text/javascript" charset="utf-8"></script> <script src="vue-router.js" type="text/javascript" charset="utf-8"></script> <style type="text/css"> .router-link-active{ color: red; } </style> </head> <body> <div id="out"> <h1>路由</h1> <!--路由導航標籤--> <router-link to="/home/2" tag="span">首頁</router-link> <router-link to="/about" tag="span">關於</router-link> <router-link to="/other" tag="span">其他</router-link> <!--路由容器--> <router-view></router-view> </div> <template id="home"> <div> <h2>首頁--</h2> </div> </template> <template id="about"> <div> <h2>about--</h2> <button @click="tap()">跳轉到other</button> </div> </template> <template id="other"> <div> <h2>other--</h2> </div> </template> </body> <script type="text/javascript"> //定義元件 var Home={ template:"#home", mounted(){ console.log(this.$route.params) } } var About={ template:"#about", methods:{ tap(){ router.push('/other') } } } var Other={ template:"#other" } // 配置路由規則 var routes=[ {path:'/home/:id',component:Home}, {path:'/about',component:About}, {path:'/other',component:Other} ] // 例項化路由物件 var router=new VueRouter({ routes:routes }) // 路由掛載 var vm=new Vue({ el:'#out', router:router }) // 前端路由適合做單頁面應用(SPA) //params--一般用來傳遞單個數據 //query--一般用來傳遞多個數據 </script> </html>