安装vue-router3
$ yarn add vue-router@3 (vue2不匹配vue-router4!)
配置router
创建router/index.js文件
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "home",
component: () => import("@/pages/home.vue"),
},
{
path: "/test",
name: "test",
component: () => import("@/pages/test.vue"),
},
];
export default new VueRouter({
routes,
});
main.js文件引入并使用router
import Vue from "vue";
import App from "./App.vue";
import router from "@/router/index";
Vue.config.productionTip = false;
new Vue({
render: (h) => h(App),
router,
}).$mount("#app");
App.vue文件使用router
<template>
<div id="app">
// 这里
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "App",
};
</script>
使用router
创建测试路由文件testRoutes.js
export const testRoutes = [
{
path: "/test",
name: "test",
component: () => import("@/pages/test/index.vue"),
redirect: "/test/testA", // 默认跳转testA
children: [
{
path: "testA",
component: () => import("@/pages/test/testA.vue"),
},
{
path: "testB",
component: () => import("@/pages/test/testB.vue"),
},
],
},
];
route/index.js引入testRoutes.js
import Vue from "vue";
import VueRouter from "vue-router";
import { testRoutes } from "./testRouter"; // 测试路由
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "home",
component: () => import("@/pages/home.vue"),
},
...testRoutes,
];
export default new VueRouter({
routes,
});
test/index.vue文件
<template>
<div>
<h2>测试</h2>
<button @click="toPage('testA')">测试A</button>
<button @click="toPage('testB')">测试B</button>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "test-page",
methods: {
toPage(path) {
this.$router.push({
path,
});
},
},
};
</script>
test/testA.vue文件
<template>
<div>测试文件A</div>
</template>
<script>
export default {};
</script>
test/testB.vue文件
<template>
<div>测试文件B</div>
</template>
<script>
export default {};
</script>