企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
>[success] # 安装即使用 * 使用npm 安装 ~~~ npm install vue-router@4 ~~~ >[danger] ##### 使用 1. 导入`import { createRouter} from 'vue-router' ` 创建 `router` 实例 2. 配置参数,其中`routes` 选项配置路由和组件映射关系,`history` 配置是`hash` 还是 `history` 模式 ~~~ import { createWebHashHistory, createWebHistory } from 'vue-router' history: createWebHashHistory(), // hash history: createWebHistory(), // history ~~~ 3. 将`router` 实例挂在到 `vue 根实例上` 4. 使用路由: 通过`<router-link>`和`<router-view>` * router/index.js ~~~ js import { createRouter, createWebHistory } from 'vue-router' const router = createRouter({ routes: [ { path: '/home', component: () => import('@/view/Home.vue'), }, { path: '/about', component: () => import('@/view/About.vue'), }, ], history: createWebHistory(), // 开启history模式 }) export default router ~~~ * main.js ~~~ import { createApp } from 'vue' import App from './App.vue' import router from './router' const app = createApp(App) app.use(router) // 绑定路由 app.mount('#app') ~~~ * App.vue ~~~ html <template> <router-link to="/home">home</router-link> <router-link to="/about">about</router-link> <router-view /> </template> <script setup></script> <style></style> ~~~ >[danger] ##### 挂载 使用 `app.use(router)` 后就可将`router `实例挂载到`vue `上,如果是 `option API` 可以使用`this.$router`的形式访问它,并且以`this.$route`的形式访问当前路由 ~~~ // Home.vue export default { computed: { username() { // 我们很快就会看到 `params` 是什么 return this.$route.params.username }, }, methods: { goToDashboard() { if (isAuthenticated) { this.$router.push('/dashboard') } else { this.$router.push('/login') } }, }, } ~~~ 使用的是 `Composition API ` 则可以使用` import { useRouter, useRoute } from 'vue-router'` 形式使用