Vue路由篇之动态路由匹配
详情请见注释
<style>
.active{
font-size: 100px;
color:red
}
</style>
<div id="app">
<ul>
<router-link tag='li' to='/position/35/city/10' exact active-class="active">前端研发</router-link> <!-- exact精确匹配可以解决首页和职位同时选中样式,注意有时候发现选中的样式不对,可以考虑是否是精准匹配的问题 -->
<router-link tag='li' to='/position' exact active-class="active">职位</router-link> <!-- 路由要进行跳转 router-link作为跳转标签 -->
<router-link tag='li'to='/search' exact active-class="active">搜索</router-link>
</ul>
<router-view></router-view> <!-- 链接的内容视图,只要跟router-link平级 就会把router-link的内容放在router-view里面 -->
<!-- 标签内属性to:'路径' active-class 点击选中的样式 -->
<!-- router-link默认是a标签 要把它变为其他标签可以用tag='li' -->
</div>
<script>
const position={//定义局部组件
template:`<div>position</div>`
}
const search={
template:`<div>search</div>`
}
var router=new VueRouter({//VueRouter的实例 路由的匹配顺序是从上到下依次匹配
mode:'hash',//默认是哈希 也可以配history
routes:[{
path:'/position',//路径
component:position//注册组件,组件的模板可以写在外面,也可以向下面动态参数一样,模板写在里面
},{
path:'/search',
component:search
}
,{
path:'/position/:id/city/:cid',//动态参数 可以一个参数也可以多个参数 多个参数如此 单个参数就去掉/city及之后,与router-link对应
component:{
template:`
<div>position detail {{$route.params}}</div>
`
// 只取一个对象用$route 匹配路由时参数可以在$route.params取
}
},
{
path:'*',//*代表所有 因为路由匹配是自上到下匹配 上面的路径都没匹配到,到这里就会直接匹配除了上面路径的任意路径,从而跳到404页面
component:{
template:`<h1>404 page not found..</h1>`
}
}]
})
var vm=new Vue({
router:router,//router=new好的实例。。。不要忘了,这里要你new好的实例放到Vue实例中!!!
el:"#app"
})
</script>
下面是实测: