简单使用
完整代码:https://codesandbox.io/s/elastic-dust-0hwun
import Vue from "vue";
// 1. 引入vue-router
import Router from "vue-router";
import HelloWorld from "../components/HelloWorld";
import A from "../components/A";
// 2. 注册成vue插件
Vue.use(Router);
// 3. 新建router实例,传递配置信息
export default new Router({
routes: [
{
path: "/hello",
component: HelloWorld
},
{
path: "/a",
component: A
}
]
});
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
Vue.config.productionTip = false;
new Vue({
render: (h) => h(App),
router // 将router实例注入到vue根组件实例
}).$mount("#app");
使用router-link指定跳转的path,在router-view中显示内容
<template>
<div id="app">
<!-- router-link跳转 -->
<router-link to="/hello">Hello</router-link> |
<router-link to="/A">aaa</router-link>
<!-- router-view显示组件内容 -->
<router-view />
</div>
</template>
我们可以使用this.$router
访问路由器,$router包含push,go,forward,back等方法
也可以通过 this.$route
访问当前路由
一条route里有多个组件
使用components对象
export default new Router({
routes: [
{
path: "/hello",
component: HelloWorld
},
{
path: "/ab",
components: {
main: A,
side: B
}
}
]
});
router-view指定name
<template>
<div id="app">
<router-link to="hello">hello</router-link> |
<router-link to="ab">ab</router-link>
<router-view />
<router-view name="main" />
<router-view name="side" />
</div>
</template>
完整代码:https://codesandbox.io/s/damp-pine-rpxf8
传递参数
1.每条route必须添加name
2.path后加 /:xxx
export default new Router({
routes: [
{
name: "hello",
path: "/hello/:msg",
component: HelloWorld
},
{
name: "aaa",
path: "/a/:msg&author=:name",
component: A
}
]
});
3.router-link传入包含name和params的对象
<template>
<div id="app">
<!-- router-link跳转 -->
<router-link :to="{ name: 'hello', params: { msg: '我是hello world' } }"
>Hello</router-link
>
|
<router-link :to="{ name: 'aaa', params: { msg: '我是aaa', name: '小王' } }"
>aaa</router-link
>
<!-- router-view显示组件内容 -->
<router-view />
</div>
</template>
4.各组件可以通过this.$route.params
获取传递的参数
完整代码:https://codesandbox.io/s/jolly-lamarr-6jf9y
路由重定向
用redirect实现重定向
const routes: Array<RouteConfig> = [
{
path: '/',
redirect: '/money'
}
]