Vue3 vue-router 快速上手

  1. 说明

    1. Vue Router 是 Vue.js 的官方路由。它与 Vue.js 核心深度集成,让用 Vue.js 构建单页应用变得轻而易举。功能包括:

      1. 嵌套路由映射

      2. 动态路由选择

      3. 模块化、基于组件的路由配置

      4. 路由参数、查询、通配符

      5. 展示由 Vue.js 的过渡系统提供的过渡效果

      6. 细致的导航控制

      7. 自动激活 CSS 类的链接

      8. HTML5 history 模式或 hash 模式

      9. 可定制的滚动行为

      10. URL 的正确编码

  2. 安装

    pnpm add vue-router@4
  3. 配置

    1. 创建一个router文件夹,在文件夹下新建两个文件,分别是routes.ts和index.ts
    2. router.ts
      export const constantRoute = [
          {
              path: '/home/:id',
              component:()=> import('../vue-base/home.vue')
          },
          {
              path: '/about',
              component:()=> import('../vue-base/about.vue')
          }
      
      ]
    3. index.ts
      //通过vue-router插件实现模板路由配置
      import {createRouter,createWebHashHistory} from 'vue-router'
      import {constantRoute} from './routes'
      //创建路由器
      let router = createRouter({
          history:createWebHashHistory(),
          routes:constantRoute
      })
      export default router
    4. 在main.ts文件中注册插件
      import router from './router';
      app.use(router)
      
    5. 在app.vue设置出口
      <script setup lang="ts">
      </script>
      
      <template>
        <div>
          <router-view></router-view>
        </div>
      </template>
      <style scoped>
      </style>
      
  4. 使用

    1. 为了举例,创建了home.vue和about.vue两个文件
    2. home.vue
      <template>
          <div>
              <h1>home</h1>
              <router-link to="/about">Go to About</router-link>
          </div>
      </template>
      
      <script setup lang="ts">
      import { useRouter } from 'vue-router'; 
      let router = useRouter()
      console.log(router.currentRoute.value.params)
      </script>
      
      <style scoped></style>
    3. about.vue
      <template>
          <div>
              <h1>about</h1>
              <router-link to="/home">Go to Home</router-link>
          </div>
      </template>
      
      <script setup lang="ts">
      
      </script>
      
      <style scoped></style>
    4. 效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值