当前位置:   article > 正文

Vue3--Vue-Router的使用_通过cdn从官网下载vue-router.js文件

通过cdn从官网下载vue-router.js文件

Vue3–Vue-Router的使用



前言

使用Vue.js框架构建单页应用往往需要页面的跳转,如何在单页面中显示不同组件呢?那就是使用Vue Router。这篇文章将介绍Vue Router的入门使用。


一、Vue Router是什么?

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

  • 嵌套路由映射
  • 动态路由选择
  • 模块化、基于组件的路由配置
  • 路由参数、查询、通配符
  • 展示由 Vue.js 的过渡系统提供的过渡效果
  • 细致的导航控制
  • 自动激活 CSS 类的链接
  • HTML5 history 模式或 hash 模式
  • 可定制的滚动行为
  • URL 的正确编码

二、使用步骤

1.安装Vue Router

直接下载 / CDN

https://unpkg.com/vue-router@4

npm

npm install vue-router@4
  • 1

yarn

yarn add vue-router@4
  • 1

2.配置

JavaScript

2.1 新建router.js

<!-- 导入vue-router -->
import { createRouter, createWebHistory } from 'vue-router'
<!-- 创建Router -->
const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            component: () => import('@/views/WelcomeView.vue'),
            <!-- 如果在页面中想渲染多个组件,就将组件添加进children中 -->
            children: [
                {
                    path: '/',
                    component: () => import('@/components/welcome/LoginPage.vue')
                }, {
                    path: '/register',
                    component: () => import('@/components/welcome/RegisterPage.vue')
                }, {
                    path: '/forget',
                    component: () => import('@/components/welcome/ForgetPage.vue')
                }
            ]
        },
        {
            path: '/manage',
            component: () => import('@/views/ManageView.vue'),
            children: [
                {
                    path: '/userList',
                    component: () => import('@/components/manage/userListPage.vue')
                }, {
                    path: '/gymList',
                    component: () => import('@/components/manage/gymListPage.vue')
                }
                
            ]
        }
    ]
})
// 暴露router
export default router
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

2.2在main.js文件中导入Vue Router

import router from './router  
const app = createApp(App)
app.use(router)'
app.mount('#app')
  • 1
  • 2
  • 3
  • 4

2.3HTML

<!--使用 router-link 组件进行导航 -->
<!--通过传递 `to` 来指定链接 -->
<router-link to="/">To Index</router-link>
<router-link to="/login">登录</router-link>

<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

提示:在单页面中如果你把组件添加到router中但是显示不出来,很可能时没有添加:<router-view></router-view>

总结

以上就是Vue Router的入门使用了,更多用法可以参考官方文档

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读