Vue3中VueRouter基本用法及与Vue2中路由使用差异解析

Vue Router 在 Vue3 中被重写,使用了 Vue3 的 Composition API。使用上跟Vue2 相比有些不同,需要注意。

首先,让我们来看一下 Vue3 中 VueRouter 的基本使用方法:

  1. 安装 Vue Router:
npm install vue-router@next
  1. 创建一个 router.js 文件,并设置你的路由:
import { createRouter, createWebHistory } from 'vue-router'
import HomeComponent from './components/HomeComponent.vue'
import AboutComponent from './components/AboutComponent.vue'

export const router = createRouter({
  history: createWebHistory(), //注意这里,方式不同
  routes: [
    { path: '/', component: HomeComponent },
    { path: '/about', component: AboutComponent },
  ],
})
  1. 在你的 main.js 文件中安装路由:
import { createApp } from 'vue'
import App from './App.vue'
import { router } from './router.js'

//这里,用的是use
createApp(App).use(router).mount('#app')
  1. 现在,你可以在你的组件中使用 <router-link><router-view>
<template>
  <nav>
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
  </nav>
  <router-view/>
</template>

接下来,让我们看一下 Vue3 和 Vue2 在使用VueRouter 时的主要差异:

  • Vue Router 在 Vue3 中被重写,使用了 Vue3 的 Composition API。这意味着你可以在任何组件中使用 useRouteruseRoute 来分别获取 router 实例和当前路由。

  • Vue3 支持异步组件,这意味着你可以在路由配置中直接使用动态 import() 语法来导入组件,无需使用 Vue.component

  • Vue3 中的 <router-link> 不再支持 tag 属性,而是引入了新的 v-slot API 来自定义链接的渲染方式。

  • Vue3 中的 Vue Router 对 Vue2 的 API 进行了一些更改,例如,mode: 'history' 被更改为 history: createWebHistory()base 属性被移动到了 createWebHistory 函数中。

更多细节如动态路由、编程式导航、路由守卫等原理相同,写法略不同,参考:https://router.vuejs.org/zh/introduction.html

相关推荐

  1. vue3vue2nextTick源码

    2024-06-16 12:34:04       50 阅读
  2. Vue$set用法

    2024-06-16 12:34:04       43 阅读
  3. vue2 vue3差异汇总

    2024-06-16 12:34:04       33 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-16 12:34:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-16 12:34:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-16 12:34:04       82 阅读
  4. Python语言-面向对象

    2024-06-16 12:34:04       91 阅读

热门阅读

  1. vue中的组件通信

    2024-06-16 12:34:04       47 阅读
  2. 使用C++调用VTK库实现三维显示示例

    2024-06-16 12:34:04       40 阅读
  3. 微信小程序(2)

    2024-06-16 12:34:04       41 阅读
  4. Linux系统内核作用

    2024-06-16 12:34:04       31 阅读
  5. Oracle的listagg的用法和例子

    2024-06-16 12:34:04       25 阅读