安装
npm install vue-router
或
yarn add vue-router
使用
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes: Array<RouteConfig> = [
{
path:'/labels',
component:Labels
},
{
path:'/statistics',
component:Statistics
},
{
path:'*',
component:NotFound
},
];
const router = new VueRouter({
routes
});
挂载到app
new Vue({
router,
render: h => h(App)
}).$mount('#app');
- 在vue-router中,用到两个重要标签router-view和router-link。 router-link to属性接上路径,被点击时,routes中路径和to 后面的路径匹配,router-view展示对应组件的内容
<div>
<router-link to="/xxx" > 显示</router-link>
</div>
路由匹配到的组件将在router-view显示
<div id="app">
<router-view/>
</div>
模式
- vue-router默认hash默认,在路径中会带有#,当URL改变时,页面不会重新加载,
- 如果不想很丑的hash ,可以history模式,这种模式就像正常的URL跳转,不用自己重新加载页面,但需要后台配置支持,因为应用是单页客户端应用,如果后台没有正确的配置,当用户直接访问正常的URL就会返回404.
默认路由和404路由
如果想匹配默认路由,可以使用"/",当前默认路由就是money,如果想写除我们自己设置的路径以外的其他任意路径为404,我们可以使用通配符"*",
const routes: Array<RouteConfig> = [
{
path:'/',
redirect:'/money'
}
,
{
path:'/labels',
component:Labels
},
{
path:'*',
component:NotFound
},
];