注意vue-router版本,我用的是"vue-router": "^4.0.0-alpha.6"

官网的使用步骤

// 1. Define route components.
// These can be imported from other files
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }

// 2. Define some routes
// Each route should map to a component.
// We'll talk about nested routes later.
const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
]

// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = VueRouter.createRouter({
  // 4. Provide the history implementation to use. We are using the hash history for simplicity here.
  history: VueRouter.createWebHashHistory(),
  routes, // short for `routes: routes`
})

// 5. Create and mount the root instance.
const app = Vue.createApp({})
// Make sure to _use_ the router instance to make the
// whole app router-aware.
app.use(router)

app.mount('#app')

// Now the app has started!

自己来配

  • 定义router.js
import { createRouter, createWebHashHistory } from "vue-router";
import Home from "../views/Home.vue";
const routes = [
	{
		path: "/home",
		name: "Home",
		component: Home,
	},
	{
		path: "/test",
		name: "Test",
		component: () =>
			import(/* webpackChunkName: "about" */ "../views/Test.vue"),
	},
];

const router = createRouter({
	history: createWebHashHistory(),
	routes,
});

export default router;
  • main.js入口文件引入
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router/index";
import "./index.css";

const app = createApp(App);
app.use(router);//注意顺序
app.mount("#app");
  • 使用
<template>
    <div>
        <router-link to="/home">Home</router-link>
        <router-link to='/test'>Test</router-link>
    </div>
    <router-view></router-view>
</template>

<script>
import { onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
export default {
    setup(props, context) {
        onMounted(() => {
            console.log(route);
            console.log(router);
        });

        const route = useRoute();
        const router = useRouter();

        return {};
    },
};
</script>

在这里插入图片描述
在这里插入图片描述

这样就可以像以前那样用路由了

有一个小细节

{
	path: "/:home(\\d+)", //正则匹配
	name: "Home",
	alias: "/home", //别名,可以数组['/home1','/home2']
	component: Home,
},
  • 别名alias
    在这里插入图片描述
  • 正则
    在这里插入图片描述
  • 别名alias数组
    在这里插入图片描述

详细了解可以看文档vue-router

Logo

前往低代码交流专区

更多推荐