router文件夾下的index.js文件vue
import Vue from 'vue';vue-router
import Router from 'vue-router'編程
Vue.use(Router)app
export default new Router({this
linkActiveClass:'selected',spa
routes:[component
{router
path:'/',對象
redirect:'/home'路由
},
{
path:'/home',
name:'Home',
component:( ) => import('./view/home')
}
]
})
main.js文件
import Vue from 'vue'
import App from './App'
import router from './router'
new Vue({
el:'#app',
router,
components:{ App },
template:'<App />'
})
路由跳轉
聲明式
<router-link to='/home'>home</router-link>
編程式
this.$router.push('/home')
渲染路由匹配的組件
<router-view></router-view>
路由傳參的二種方式
params式傳參:/home/1/2
this.$route.params.id或{{$route.params.id}}
使用params式傳參時須要在對應路由的跳轉地址中設置參數名
query式傳參:/home?id=1&age=18
this.$route.query.id或{{$route.query.id}}
<router-link to='/home/1'>home</router-link>
{path:'/home/:id',component:Home}
在Home組件中使用this.$route.params.id接收地址中的參數,或者{{$route.params.id}}
聲明式
聲明式常見方式
<router-link to="/home">home</router-link>
對象的方式
<router-link :to="{path:'/home'}">home</router-link>
命名路由
<router-link :to="{name:'Home'}">home</router-link>
直接路由帶查詢參數query,地址欄變成/home?id=10
<router-link :to="{path:'/home',query:{id:10}}">home</router-link>
命名路由帶查詢參數query,地址欄變成/home?id=10
<router-link :to="{name:'Home',query:{id:10}}">home</router-link>
直接路由帶路由參數params,params不生效,若是提供了path,params會被忽略
<router-link :to="{path:'/home',params:{id:10}}">home</router-link>
命名路由帶路由參數params,地址欄變成/home/10
<router-link :to="{name:'Home',params:{id:10}}">home</router-link>
編程式
this.$router.push('/home')
this.$router.push({path:'/home'})
this.$router.push({name:'home'})
this.$router.push({path:'/home',query:{id:10}})
this.$router.push({name:'home',query:{id:10}})
path搭配params使用不生效
this.$router.push({path:'/home',params:{id:10}})
this.$router.push({name:'home',params:{id:10}})
二級路由
{
path:'/list',
name:'list',
component:( ) => import('../views/List.vue'),
children:[
{
path:'/list/info', // path:'info' 也能夠
name:listInfo,
component:( ) => import('../view/Banner.vue')
}
]
}
二級路由展現在對應一級路由組件的<router-link />
二級路由在切換的時候,使用this.route.path是獲取不到實時路由地址的,this.route.path只能在一級路由切換時,實時獲取路由地址
想要在二級路由切換獲取實時路由地址,須要使用watch監聽,監聽路由的變化
watch:{
$route(to,from){
console.log(to.path)
}
}