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