vue-router 的设置步骤 vue-router基础@stage3---week2--day5

2023-10-18 12:30

本文主要是介绍vue-router 的设置步骤 vue-router基础@stage3---week2--day5,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

vue-router [版本 3.x]

SPA ( single page App ) 单页面应用

对应着 多页面应用

  • 有多个 html 文件,通过 a 标签的连接联通各个页面
  • 缺点
    • 开发起来太冗余,编译、压缩很耗时间
    • 页面之间的跳转速度太慢,这个时候就会出现一个严重的问题,白屏
  1. 单页面应用
    • 不需要刷新页面,因为它就是一个页面
    • 这个页面内容在切换
    • 单页面内容之间的切换要想实现我们就是用路由了
    • 如今我们的 app、后台管理系统 主要的开发形式就是 spa
vue路由功能图示

vue-router-基础

src 目录下

  1. 在 components 文件夹写一个单页面组件 Navs.vue,并将其导出 Navs 的选项(ES6 的 module 模块化)
<template><article class="container"><section class="row"><!-- 导航区域 --><nav class="nav nav-pills flex-column flex-sm-row"><router-linkclass="flex-sm-fill text-sm-center nav-link"active-class="active"keep-alivetag="span"to="/home">首页</router-link><router-linkclass="flex-sm-fill text-sm-center nav-link"active-class="active"keep-alivetag="span"to="/category">分类</router-link><router-linkclass="flex-sm-fill text-sm-center nav-link"active-class="active"keep-alivetag="span"to="/recommend">推荐</router-link><router-linkclass="flex-sm-fill text-sm-center nav-link"active-class="active"keep-alivetag="span"to="/shopcar">购物车</router-link><router-linkclass="flex-sm-fill text-sm-center nav-link"active-class="active"keep-alivetag="span"to="/mine">个人中心</router-link></nav></section>·<!-- 路由展示区 --><section class="row"><router-view></router-view></section></article>
</template><script>export default {name: "Navs"};
</script><!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus"></style>
  1. 在 App.vue 中导入 Navs,在 App 的组件中注册,并在其模版中添加标签
<template><div id="app"><img alt="Vue logo" src="./assets/logo.png" /><Navs /></div>
</template><script>import Navs from "./components/Navs.vue";export default {name: "app",components: {Navs}};
</script>
<style lang="stylus"></style>
  1. 创建路由的配置文件: 新建一个 router 文件夹,写入一个 index.js 文件,进行路由配置

    需要提前下载 vue-router
    $ yarn add vue-router

Vue 路由模式
vue 路由的 mode(模式)有几种, 分别是什么?在那些环境下运行?

  • hash: 使用 URL hash 值来作路由。支持所有浏览器,包括不支持 HTML5 History Api 的浏览器。 #/home
  • history: 依赖 HTML5 History API 和服务器配置。【需要后端支持】 /home
  • abstract: 支持所有 JavaScript 运行环境,如 Node.js 服务器端。如果发现没有浏览器的 API,路由会自动强制进入这个模式。【 这个模式不常用 】
  • hash/history 常用于浏览器端,abstract 用于服务端
//导入vue模块
import Vue from "vue";//导入vue-router模块
import VueRouter from "vue-router";//需要在router 文件夹 下写入一个routes.js文件(路由表),以便在此处导入
//导入路由表
import routes from "./routes";//使用中间件
Vue.use(VueRouter);//实例化VueRouter
const router = new VueRouter({mode: "history", //路由模式routes //引入路由表
});//导出router模块
export default router;
//需要在main.js引用;
  1. 在 router 文件夹下面写入 routers.js 路由表文件
//导入路由文件模块
//需要后面的写入
import Home from "../pages/home";import Category from "../pages/category";import Recommend from "../pages/recommend";import ShopCar from "../pages/shopcar";import Mine from "../pages/mine";const routes = [{path: "/home", //路由路径component: Home //当前路由路径对应的组件},{path: "/category", //路由路径component: Category //当前路由路径对应的组件},{path: "/recommend", //路由路径component: Recommend //当前路由路径对应的组件},{path: "/shopcar", //路由路径component: ShopCar //当前路由路径对应的组件},{path: "/mine", //路由路径component: Mine //当前路由路径对应的组件}
];// 导出模块export default routes;
  1. router 文件夹中的 index.js 需要在入口文件 main.js 中导入使用
    入口文件 main.js 中引入路由实例 router , 然后在根实例中注册
import Vue from "vue";
import App from "./App.vue";
import router from "./router";Vue.config.productionTip = false;new Vue({render: h => h(App),router //在根实例中注入路由
}).$mount("#app");
  1. 现在来处理第 4 步未处理的 pages 下的路由页面,首先创建 pages 文件夹,
    6.1 在 pages 文件夹下面,创建 home 文件夹,并在其内写入 index.vue
<template><article><div><p>Home页面</p></div></article>
</template><script>export default {name: "Home"};
</script><style></style>

6.2 在 pages(放页面组件的地方) 文件夹下面,创建 category 文件夹,并在其内写入 index.vue

<template><article><div><p>Category页面</p></div></article>
</template><script>export default {name: "Category"};
</script><style></style>
  1. 用 router-view 组件来接受 routes 配置中的 component 选项: 在 App.vue 或 components 文件夹下的 Navs 或其他模版中使用
<router-view></router-view>

components 文件夹下的 Navs.vue

<template><article class="container"><section class="row"><!-- 导航区域 --><nav class="nav nav-pills flex-column flex-sm-row"><router-linkclass="flex-sm-fill text-sm-center nav-link"active-class="active"keep-alivetag="span"to="/home">首页</router-link><router-linkclass="flex-sm-fill text-sm-center nav-link"active-class="active"keep-alivetag="span"to="/category">分类</router-link><router-linkclass="flex-sm-fill text-sm-center nav-link"active-class="active"keep-alivetag="span"to="/recommend">推荐</router-link><router-linkclass="flex-sm-fill text-sm-center nav-link"active-class="active"keep-alivetag="span"to="/shopcar">购物车</router-link><router-linkclass="flex-sm-fill text-sm-center nav-link"active-class="active"keep-alivetag="span"to="/mine">个人中心</router-link></nav></section>·<!-- 路由展示区 --><section class="row"><router-view></router-view></section></article>
</template><script>export default {name: "Navs"};
</script><!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus"></style>
  1. 我们可以使用 router-link 组件 进行页面跳转

    components 文件夹下的 Navs.vue

    • router-link 组件身上加 to 属性 , to 属性的属性值 为 routes 配置中的 path 选项
    • router-link 组件默认会解析为 a 标签
    • router-link 组件加 tag 属性可以解析为 任何标签
    • router-link 组件加 active-class 属性 可以实现路由激活
    • router-link 组件加 keep-alive 属性, 可以实现路由组件的动态缓存
  2. 如果你使用的是 hash , 那么a标签就可以了、

  3. 如果你使用 history , 那么我们最好将a标签改成 router-link 这个组件

    • router-link 这个组件 身上必须要有一个 to 属性
    • router-link 这个组件身上加一个 keep-alive属性可以进行浏览器缓存

    案例看上一个即可

9.当页面第一次的打开的时候, 需要做一个重定向, 就是要自动跳转到 /home 这个路由上
在 router 文件夹下 routes.js 文件下,

import Home from "../pages/home";import Category from "../pages/category";import Recommend from "../pages/recommend";import ShopCar from "../pages/shopcar";import Mine from "../pages/mine";const routes = [{path: "/", //要求这个路由的配置要放在路由表的最上方redirect: "/home" //重定向},{path: "/home", //路由路径component: Home //当前路由路径对应的组件},{path: "/category", //路由路径component: Category //当前路由路径对应的组件},{path: "/recommend", //路由路径component: Recommend //当前路由路径对应的组件},{path: "/shopcar", //路由路径component: ShopCar //当前路由路径对应的组件},{path: "/mine", //路由路径component: Mine //当前路由路径对应的组件}
];// 导出模块export default routes;
  1. 业务: 错误路由匹配

在 router 文件夹下 routes.js 文件下,
错误路由匹配,vue 规定这个必须放在最下面,它必须将上面的路由全找一遍,找不到才用当前这个

import Home from "../pages/home";import Category from "../pages/category";import Recommend from "../pages/recommend";import ShopCar from "../pages/shopcar";import Mine from "../pages/mine";const routes = [{path: "/", //路由路径redirect: "/home"},{path: "/home", //路由路径component: Home //当前路由路径对应的组件},{path: "/category", //路由路径component: Category //当前路由路径对应的组件},{path: "/recommend", //路由路径component: Recommend //当前路由路径对应的组件},{path: "/shopcar", //路由路径component: ShopCar //当前路由路径对应的组件},{path: "/mine", //路由路径component: Mine //当前路由路径对应的组件},{path: "/error", //路由路径component: Error //当前路由路径对应的组件},{path: "**", //错误路由匹配,vue规定这个必须放在最下面,它必须将上面的路由全找一遍,找不到才用当前这个redirect: "/error" //重定向}
];// 导出模块export default routes;
  1. 二级路由
  • 注意: 写好配置之后,不要忘记了, 在对应的一级路由的组件中书写 路由展示区域
import Home from '../pages/home';import Category from '../pages/category';import Recommend from '../pages/recommend';import ShopCar from '../pages/shopcar';import Mine from '../pages/mine';import Error from '../pages/error';import Zhy from '../pages/home/children/zhy.vue';import Lsy from '../pages/home/children/lsy.vue';const routes = [{path: '/', //路由路径redirect: '/home'},{path: '/home', //路由路径component: Home, //当前路由路径对应的组件children: [{path: 'zhy', //这里不写‘/’component: Zhy},{path: 'lsy',component: Lsy}]},{path: '/category', //路由路径component: Category //当前路由路径对应的组件},{path: '/recommend', //路由路径component: Recommend //当前路由路径对应的组件},{path: '/shopcar', //路由路径component: ShopCar //当前路由路径对应的组件},{path: '/mine', //路由路径component: Mine //当前路由路径对应的组件},{path: '/error', //路由路径component: Error //当前路由路径对应的组件},{path: '**', //错误路由匹配,vue规定这个必须放在最下面,它必须将上面的路由全找一遍,找不到才用当前这个redirect: '/error' //重定向},];// 导出模块export default routes;

pages>home>home.vue
注意: to="/home/zhy"

<template><article><div><p>Home页面</p><router-link class="flex-sm-fill text-sm-center nav-link" active-class="active" keep-alive tag="span" to="/home/zhy" > 张浩雨么么哒 </router-link><router-link class="flex-sm-fill text-sm-center nav-link" active-class="active" keep-alive tag="span" to="/home/lsy" > 李山雨么么哒 </router-link></div><!-- <Zhy></Zhy> --><router-view></router-view></article>
</template><script>
import Zhy from './children/zhy';
import Lsy from './children/lsy';
export default {name:'Home',components:{Zhy,Lsy}
};
</script><style>
</style>

12.命名路由

  • 作用: 就是简写路径了
         {path: '/shopcar',component: Shopcar,//子路由 children: [{ path: 'yyb', // 容易犯错点  /yyb X component: Yyb,name: 'yyb' //命名路由},{path: 'junge',component: Junge}]},
    
  • 使用: 单项数据绑定to属性
        <router-link :to = "{name:'yyb'}"/>

重定向

重定向也是通过 routes 配置来完成,下面例子是从 /a 重定向到 /b:

const router = new VueRouter({routes: [{ path: '/a', redirect: '/b' }]
})

重定向的目标也可以是一个命名的路由:

const router = new VueRouter({routes: [{ path: '/a', redirect: { name: 'foo' }}]
})

甚至是一个方法,动态返回重定向目标:

const router = new VueRouter({routes: [{ path: '/a', redirect: to => {// 方法接收 目标路由 作为参数// return 重定向的 字符串路径/路径对象}}]
})

注意导航守卫并没有应用在跳转路由上,而仅仅应用在其目标上。

别名

“重定向”的意思是,当用户访问 /a时,URL 将会被替换成 /b,然后匹配路由为 /b,那么“别名”又是什么呢?
/a 的别名是 /b,意味着,当用户访问 /b 时,URL 会保持为 /b,但是路由匹配则为 /a,就像用户访问 /a 一样。
上面对应的路由配置为:

const router = new VueRouter({routes: [{ path: '/a', component: A, alias: '/b' }]
})

“别名”的功能让你可以自由地将 UI 结构映射到任意的 URL,而不是受限于配置的嵌套路由结构。

编程式的导航

  • 除了使用 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。
router.push(location, onComplete?, onAbort?)

注意:在 Vue 实例内部,你可以通过 r o u t e r 访 问 路 由 实 例 。 因 此 你 可 以 调 用 < f o n t > t h i s . router 访问路由实例。因此你可以调用 <font>this. router访<font>this.router.push。

  • 想要导航到不同的 URL,则使用 router.push 方法。这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。

  • 当你点击 时,这个方法会在内部调用,所以说,点击 等同于调用 router.push(…)。

    声明式编程式
    < router-link :to="…">router.push(…)

该方法的参数可以是一个字符串路径,或者一个描述地址的对象。例如:

// 字符串
router.push('home')// 对象
router.push({ path: 'home' })// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

注意:如果提供了 path,params 会被忽略,上述例子中的 query 并不属于这种情况。取而代之的是下面例子的做法,你需要提供路由的 name 或手写完整的带有参数的 path:

const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 这里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user

同样的规则也适用于 router-link 组件的 to 属性。

router.replace(location, onComplete?, onAbort?)

跟 router.push 很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。

声明式编程式
< router-link :to="…" replace>router.replace(…)
router.go(n)

这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)。

// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)// 后退一步记录,等同于 history.back()
router.go(-1)// 前进 3 步记录
router.go(3)// 如果 history 记录不够用,那就默默地失败呗
router.go(-100)
router.go(100)

这篇关于vue-router 的设置步骤 vue-router基础@stage3---week2--day5的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/232575

相关文章

Nginx部署HTTP/3的实现步骤

《Nginx部署HTTP/3的实现步骤》本文介绍了在Nginx中部署HTTP/3的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录前提条件第一步:安装必要的依赖库第二步:获取并构建 BoringSSL第三步:获取 Nginx

Vue和React受控组件的区别小结

《Vue和React受控组件的区别小结》本文主要介绍了Vue和React受控组件的区别小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录背景React 的实现vue3 的实现写法一:直接修改事件参数写法二:通过ref引用 DOMVu

Vue3绑定props默认值问题

《Vue3绑定props默认值问题》使用Vue3的defineProps配合TypeScript的interface定义props类型,并通过withDefaults设置默认值,使组件能安全访问传入的... 目录前言步骤步骤1:使用 defineProps 定义 Props步骤2:设置默认值总结前言使用T

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp

从基础到高级详解Python数值格式化输出的完全指南

《从基础到高级详解Python数值格式化输出的完全指南》在数据分析、金融计算和科学报告领域,数值格式化是提升可读性和专业性的关键技术,本文将深入解析Python中数值格式化输出的相关方法,感兴趣的小伙... 目录引言:数值格式化的核心价值一、基础格式化方法1.1 三种核心格式化方式对比1.2 基础格式化示例

Python与MySQL实现数据库实时同步的详细步骤

《Python与MySQL实现数据库实时同步的详细步骤》在日常开发中,数据同步是一项常见的需求,本篇文章将使用Python和MySQL来实现数据库实时同步,我们将围绕数据变更捕获、数据处理和数据写入这... 目录前言摘要概述:数据同步方案1. 基本思路2. mysql Binlog 简介实现步骤与代码示例1

redis-sentinel基础概念及部署流程

《redis-sentinel基础概念及部署流程》RedisSentinel是Redis的高可用解决方案,通过监控主从节点、自动故障转移、通知机制及配置提供,实现集群故障恢复与服务持续可用,核心组件包... 目录一. 引言二. 核心功能三. 核心组件四. 故障转移流程五. 服务部署六. sentinel部署

Linux搭建ftp服务器的步骤

《Linux搭建ftp服务器的步骤》本文给大家分享Linux搭建ftp服务器的步骤,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录ftp搭建1:下载vsftpd工具2:下载客户端工具3:进入配置文件目录vsftpd.conf配置文件4:

从基础到进阶详解Python条件判断的实用指南

《从基础到进阶详解Python条件判断的实用指南》本文将通过15个实战案例,带你大家掌握条件判断的核心技巧,并从基础语法到高级应用一网打尽,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录​引言:条件判断为何如此重要一、基础语法:三行代码构建决策系统二、多条件分支:elif的魔法三、

Python WebSockets 库从基础到实战使用举例

《PythonWebSockets库从基础到实战使用举例》WebSocket是一种全双工、持久化的网络通信协议,适用于需要低延迟的应用,如实时聊天、股票行情推送、在线协作、多人游戏等,本文给大家介... 目录1. 引言2. 为什么使用 WebSocket?3. 安装 WebSockets 库4. 使用 We