安装最新版本的vue-router。(一定要安装最新版本的)
npm install vue-router@next
配置路由。
//route/index.js import { createRouter, createWebHistory } from "vue-router" import About from '../components/About.vue' const Home = () => import("../components/Home.vue") const routes = [ { path: "/", redirect: "/home" }, { path: "/home", name: "home", component: Home }, { path: "/about", name: "about", component: About } ] export default router = createRouter({ history: createWebHistory(), routes: routes })
main.js文件
import router from './route' const app = createApp(App) app.use(router) app.mount('#app')
vue3中没有this,但是提供了两个api。useRouter(), useRoute()
import {useRouter, useRoute} from 'vue-router' //useRouter代表的是this.$router //useRoute代表的是this.$route setup() { let router = useRouter() let route = useRoute() const skipHome = () => { router.push({ name: 'home', params: { id: 3 } }) } const skipAbout = () => { router.push("/about") } const getParams = () => { console.log(route.params) } return { skipAbout, skipHome, getParams } }