Vue3的vue-router超详细使用

这篇具有很好参考价值的文章主要介绍了Vue3的vue-router超详细使用。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

搭建vue3环境

我们使用vite来搭建vue3环境(没有安装vite需要去安装vite)

npm create vite routerStudy

在命令行选择
Vue3的vue-router超详细使用
Vue3的vue-router超详细使用

cd routerStudy
npm i
npm run dev

环境搭建成功!!
Vue3的vue-router超详细使用

vue-router入门(宝宝模式)

  1. 下载vue-router
npm i vue-router@4
  1. 新建以下文件
    src/components/File1.vue
<template>
    <div>
        这是文件一
    </div>
</template>

<script setup lang="ts">

</script>

<style scoped>

</style>

src/components/File2.vue

<template>
    <div>
        这是文件二
    </div>
</template>

<script setup lang="ts">

</script>

<style scoped>

</style>

在src下新建router文件夹
在router文件夹下新建router.ts:

import { createRouter,createWebHistory,createWebHashHistory } from 'vue-router'
import File1 from '../components/File1.vue'
import File2 from '../components/File2.vue'

const routes = [
    {
        path: '/',
        component:File1
    },
    {
        path: '/file2',
        component:File2
    }
]

const router = createRouter({
    // history: createWebHistory(),
    history:createWebHashHistory(),
    routes,
})

export default router;

  1. 修改src/main.ts
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router/router'

createApp(App).use(router).mount('#app')

  1. 修改src/components/HelloWorld.vue:
<script setup lang="ts">

</script>

<template>
    <router-view/>
    <button><router-link to="/">去文件一</router-link></button>
    <button><router-link to="/file2">去文件二</router-link></button> 
</template>

<style scoped>
</style>

  1. 点击按钮能够切换成功则使用成功Vue3的vue-router超详细使用

vue-router基础(青年模式)

一。动态路由匹配

1.带参数的动态路由匹配

当我们需要对每个用户加载同一个组件,但用户id不同。我们就需要在vue-router种使用一个动态字段来实现,再通过$routr.params来获取值:
Vue3的vue-router超详细使用

我们用具体实例来实现一下:

(1)修改src/router/router.ts:

import { createRouter,createWebHistory,createWebHashHistory } from 'vue-router'
import File1 from '../components/File1.vue'
import File2 from '../components/File2.vue'

const routes = [
    {
        path: '/',
        component:File1
    },
    {
        path: '/file2/:username/abc/:userid', //注意看这个
        component:File2
    }
]

const router = createRouter({
    history: createWebHistory(),
    // history:createWebHashHistory(),
    routes,
})

export default router;

(2)修改组件HelloWorld.vue:
Vue3的vue-router超详细使用
(3) 修改组件File2.vue:

<template>
    <div>
        这是文件二
    </div>
</template>

<script setup lang="ts">
import {getCurrentInstance,onMounted } from 'vue'

const instance  = getCurrentInstance() 
if (instance != null) {
    const _this = instance.appContext.config.globalProperties //vue3获取当前this
    
onMounted(() => {
    console.log(_this.$route.params)
  })
}
</script>

<style scoped>

</style>

(4)点击去文件二按钮
Vue3的vue-router超详细使用
(5)查看控制台
Vue3的vue-router超详细使用

2.捕获所有路由或404 Not Found路由

当用户在导航栏乱输一通后,路由表中没有对应的路由,这时候,就需要将用户转去404页面。那么
我们该如何处理呢?

(1)修改router/router.ts:

import { createRouter,createWebHistory,createWebHashHistory } from 'vue-router'
import File1 from '../components/File1.vue'
import File2 from '../components/File2.vue'
import NotFound from '../components/NotFound.vue'
import UserGeneric from '../components/UserGeneric.vue'


const routes = [
    {
        path: '/',
        component:File1
    },
    {
        path: '/file2/:username/abc/:userid',
        component:File2
    },
    // 将匹配所有内容并将其放在 `$route.params.pathMatch` 下
    {
        path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound
    },
    // 将匹配以 `/user-` 开头的所有内容,并将其放在 `$route.params.afterUser` 下
    {
        path: '/user-:afterUser(.*)', component: UserGeneric
    },
]

const router = createRouter({
    history: createWebHistory(),
    // history:createWebHashHistory(),
    routes,
})

export default router;

(2)新建组件NotFound.vue:

<template>
    <div>
        糟糕!页面没有找到。。。呜呜呜
    </div>
</template>

<script setup lang="ts">
import {getCurrentInstance,onMounted } from 'vue'

const instance  = getCurrentInstance() 
if (instance != null) {
    const _this = instance.appContext.config.globalProperties //vue3获取当前this
    
onMounted(() => {
    console.log(_this.$route.params)
  })
}
</script>

<style scoped>

</style>

(3)修改HelloWorld.vue
Vue3的vue-router超详细使用
(4)点击去404页面按钮(或者在地址栏乱写一通)
Vue3的vue-router超详细使用
Vue3的vue-router超详细使用
(5)出现404页面,说明运行成功!!!

二。嵌套路由

路由是可以嵌套的。例如:
Vue3的vue-router超详细使用
嵌套的理解挺简单的,我就不多叭叭了,直接上代码,看完就懂了。
(1)新建组件Children1.vue:

<template>
    <div>
        我是孩子1
    </div>
</template>

<script setup lang="ts">

</script>

<style scoped>

</style>

(2)新建组件Children2.vue:

<template>
    <div>
        我是孩子2
    </div>
</template>

<script setup lang="ts">

</script>

<style scoped>

</style>

(3)修改router/router.ts:

import { createRouter,createWebHistory,createWebHashHistory } from 'vue-router'
import File1 from '../components/File1.vue'
import File2 from '../components/File2.vue'
import NotFound from '../components/NotFound.vue'
import UserGeneric from '../components/UserGeneric.vue'
import Children1 from '../components/Children1.vue'
import Children2 from '../components/Children2.vue'



const routes = [
    {
        path: '/',
        component: File1,
        
    },
    {
        path: '/file2',
        component: File2,
        children: [  //使用嵌套路由
            {
                path: 'children1',
                component:Children1
            },
            {
                path: 'children2',
                component:Children2
            },
        ]
    },
    {
        path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound
    },
    {
        path: '/user-:afterUser(.*)', component: UserGeneric
    },
]

const router = createRouter({
    history: createWebHistory(),
    // history:createWebHashHistory(),
    routes,
})

export default router;

(4)修改组件HelloWorld.vue:
Vue3的vue-router超详细使用
(5)修改组件File2.vue:

<template>
    <div>
        这是文件二
        <div>
            我是文件二里的内容
            <router-view/>
            <button><router-link to="/file2/children1">找孩子1</router-link></button>
            <button><router-link to="/file2/children2">找孩子2</router-link></button>
        </div>
    </div>
</template>

<script setup lang="ts">

</script>

<style scoped>

</style>

(6)先点去文件二,再点击找孩子1按钮,出现即成功!!
Vue3的vue-router超详细使用

三。编程式导航

除了使用/< router-link/> 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。

1.router.push()方法的使用

(1)修改组件NotFound.vue:

<template>
    <div>
        糟糕!页面没有找到。。。呜呜呜
    </div>
</template>

<script setup lang="ts">
import {getCurrentInstance,onMounted } from 'vue'

const instance  = getCurrentInstance() 
if (instance != null) {
    const _this = instance.appContext.config.globalProperties //vue3获取当前this


    // 1.字符串路径
    _this.$router.push('/file2/children2')

    // 2.带有路径的对象
    // _this.$router.push({path:'/file2/children2'})

    // 3.命名的路由,并加上参数,让路由建立 url
    // _this.$router.push({name:'file2',params:{username:'children2'}})

    // 4.带查询参数,结果是 /register?plan=private
    // _this.$router.push({ path: '/file2/children2', query: {userid:'123'} })


    onMounted(() => {
    console.log(_this.$route.params)
  })
}
</script>

<style scoped>

</style>

(2)再点“去404页面”,发现没有去404页面了,说明编程式导航成功!!
Vue3的vue-router超详细使用

2.router.replace()方法的使用

它的作用类似于 router.push,唯一不同的是,它在导航时不会向 history 添加新记录,正如它的名字所暗示的那样——它取代了当前的条目。

修改组件NotFound.vue:

<template>
    <div>
        糟糕!页面没有找到。。。呜呜呜
    </div>
</template>

<script setup lang="ts">
import {getCurrentInstance,onMounted } from 'vue'

const instance  = getCurrentInstance() 
if (instance != null) {
    const _this = instance.appContext.config.globalProperties //vue3获取当前this

    // 一。router.push的使用: 
    // 1.字符串路径
    // _this.$router.push('/file2/children2')

    // 2.带有路径的对象
    // _this.$router.push({path:'/file2/children2'})

    // 3.命名的路由,并加上参数,让路由建立 url
    // _this.$router.push({name:'file2',params:{username:'children2'}})

    // 4.带查询参数,结果是 /register?plan=private
    // _this.$router.push({ path: '/file2/children2', query: {userid:'123'} })

    // 二。router.replace的使用:
    _this.$router.replace('/file2/children1')


    onMounted(() => {
    console.log(_this.$route.params)
  })
}
</script>

<style scoped>

</style>

3.router.go()方法的使用

修改组件NotFound.vue:文章来源地址https://www.toymoban.com/news/detail-400714.html

<template>
    <div>
        糟糕!页面没有找到。。。呜呜呜
    </div>
</template>

<script setup lang="ts">
import {getCurrentInstance,onMounted } from 'vue'

const instance  = getCurrentInstance() 
if (instance != null) {
    const _this = instance.appContext.config.globalProperties //vue3获取当前this

    // 一。router.push的使用: 
    // 1.字符串路径
    // _this.$router.push('/file2/children2')

    // 2.带有路径的对象
    // _this.$router.push({path:'/file2/children2'})

    // 3.命名的路由,并加上参数,让路由建立 url
    // _this.$router.push({name:'file2',params:{username:'children2'}})

    // 4.带查询参数,结果是 /register?plan=private
    // _this.$router.push({ path: '/file2/children2', query: {userid:'123'} })

    // 二。router.replace的使用:
    // _this.$router.replace('/file2/children1')

    // 三。router.go的使用:
    _this.$router.go(-1)  //相当于点击回退一次

    onMounted(() => {
    console.log(_this.$route.params)
  })
}
</script>

<style scoped>

</style>

到了这里,关于Vue3的vue-router超详细使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【vue 3.0 中使用vue-router详细步骤】

    1. 安装 vue-router: 2. 创建一个单独的文件: 3.main.js 配置路由: 4. 在 App.vue 中使用 router-view 组件: 5. 在路由的组件中使用 router-link 组件进行导航: 6.使用push进行跳转 以上就是在 Vue 3.0 中使用 vue-router 的详细步骤。

    2024年02月11日
    浏览(34)
  • Vite4+Pinia2+vue-router4+ElmentPlus搭建Vue3项目(组件、图标等按需引入)[保姆级]

    本文为快速搭建vite4项目,一些插件的详情就不做过多的解释,都放有官网链接,需要深入了解的小伙伴可自行查看。至于为什么选择使用vite,因为它具备着快速启动、按需编译、模块热更新的亮点。归根结底最大的特点就是 快 。vue的创始人是尤雨溪大佬,vite也是他。所以

    2023年04月19日
    浏览(42)
  • Vue3配置路由(vue-router)

    紧接上篇文章,vue3的配置与vue2是有所差别的,本文就讲述了如何配置,如果本文对你有所帮助请三连支持博主。 下面案例可供参考 使用npm命令进行安装 : npm install vue-router@4 完成后我们打开项目根目录下的 package.json 文件: 如下即为成功 这里创建 view目录,然后在view目录

    2023年04月12日
    浏览(45)
  • Vue3的vue-router路由详解

    这篇文章是接着【三分钟快速搭建Vue3+webpack项目】的内容做的开发,有基础的可以跳过 【三分钟快速搭建Vue3+webpack项目】,直接看以下的内容。 Vue3的vue-router路由详解: 首先安装路由依赖模块: 所需代码文件如下图: 图1   所需要的主要文件: index.html、index.js、App.vue in

    2024年02月01日
    浏览(49)
  • 搭建vue3,TypeScript,pinia,scss,element-plus,axios,echarts,vue-router,babylon,eslint,babel,拖拽,rem自适应大屏

    1.1、使用vite初始化项目 1.1.1、创建项目文件夹 1.1.2、进入项目文件夹 1.1.3、初始化项目 1.1.4、输入项目名称 1.1.5、选择vue 1.1.6、选择TypeScript 1.1.7、查看当前源(非必要) 1.1.8、更换为国内镜像(非必要) 1.1.9、进入项目 1.1.10、安装依赖 1.1.11、运行项目 1.1.12、修改部分报错信息

    2024年04月23日
    浏览(38)
  • Vue3/ Vue3内 Vue-router Vue3路由 完整配置流程

    (1). yarn add vue-router (2) 创建 router/index.js 文件 (3) improt 引入 createRouter improt { createRouter  }  from \\\'vue-router (4) 调用 createRouter 并定义变量名  cosnt router = createRouter()  (5) export default 导出 router  export default router  (6) createRouter() 内添加对象 并定义 history    history: createMemoryHistory()

    2023年04月08日
    浏览(66)
  • 【退役之重学前端】使用vite+vue3+vue-router,重构react+react-router前后端分离的商城后台管理系统

    前言: 对前端各个技术板块,HTML、CSS、JavaScript、ES6、vue家族,整体上能“摸其大概”。笔者计划重构一个基于react的商城后台管理系统。 —— 2024年2月16日 vue3 sass bootstrap ES7 前后端分离 分层架构 模块化开发 npm vite git

    2024年02月20日
    浏览(42)
  • Vue3 Vue-Router详解 Vue3配置hash 和 history路由、Vue3封装的路由hook函数(useRouter,useRoute)的使用 路由懒加载、路由分包处理、魔法注释的使用

     html部分 js部分  html页面使用路由传来的参数  获取router跳转id 获取 路由跳转错误地址

    2024年02月11日
    浏览(33)
  • 【vue3】13-前端路由-Vue-Router的详解: 从入门到掌握

    路由其实是网络工程中的一个术语: 在 架构一个网络 时,非常重要的两个设备就是 路由器和交换机 。 当然,目前在我们生活中 路由器 也是越来越被大家所熟知,因为我们生活中都会用到 路由器 : 事实上, 路由器 主要维护的是一个 映射表 ; 映射表 会决定数据的流向; 路由

    2024年02月09日
    浏览(35)
  • vue-router(路由)详细教程

    路由是一个比较广义和抽象的概念,路由的本质就是 对应关系 。 在开发中,路由分为: ​ 后端路由 ​ 前端路由 后端路由 概念:根据不同的用户 URL 请求,返回不同的内容 本质:URL 请求地址与服务器资源之间的对应关系 [外链图片转存失败,源站可能有防盗链机制,建议将

    2024年02月04日
    浏览(67)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包