總結:
目的 擷取 URL 裡的參數 ,例如 /login?user=xiaowang ,
如何把這個參數傳遞到組建裡
- 設定router-link URL ,讓它含有參數
- 通過 $route.query.name 格式擷取
-
應用參數 到組建去 、
代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src='../../lib/vue-2.4.0.js'></script>
<script src='../../vue-router-3.0.1.js'></script>
<style>
.router-link-active{
background-color: green;
font-size: larger;
color: aliceblue
}
.v-enter,
.v-leave-to {
opacity: 0;
transform: translateX(150px);
}
.v-enter-active,
.v-leave-active {
transition: all 0.5s ease;
}
</style>
</head>
<body>
<div id="pp">
<!-- 建立兩個button, 并通過href 找到相應組建的路由 -->
<router-link to='/login?username=xiaowang & password=test' tag="span">登入</router-link>
<router-link to='/registe' tag="span">注冊</router-link>
<!-- 用于顯示路由組建 -->
<transition mode='out-in'>
<router-view></router-view>
</transition>
</div>
<script>
// 建立兩個組模組化闆對象,讓路由能找到并顯示這個元件
var tmp1={
template:'<h1>登入: {{this.$route.query.username}}</h1>',
created(){
console.log(this.$route.query.username)
}
}
var tmp2={
template:'<h1>注冊</h1>',
}
// 建立路由對象,并設定路由的參數 ,第一個是path, 第二個是 要比對的組建
var routerObj=new VueRouter({
routes:[
{path:'/',redirect:'/login'},
{path:'/login',component:tmp1},
{path:'/registe',component:tmp2}
],
myactive: 'router-link-active',
})
new Vue({
el:'#pp',
data:{
},
methods:{
},
// 讓路由對象 和vue 執行個體 綁定關系, 用于監聽。
router: routerObj,
})
</script>
</body>
</html>