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

相关文章

使用Redis快速实现共享Session登录的详细步骤

《使用Redis快速实现共享Session登录的详细步骤》在Web开发中,Session通常用于存储用户的会话信息,允许用户在多个页面之间保持登录状态,Redis是一个开源的高性能键值数据库,广泛用于... 目录前言实现原理:步骤:使用Redis实现共享Session登录1. 引入Redis依赖2. 配置R

使用Python的requests库调用API接口的详细步骤

《使用Python的requests库调用API接口的详细步骤》使用Python的requests库调用API接口是开发中最常用的方式之一,它简化了HTTP请求的处理流程,以下是详细步骤和实战示例,涵... 目录一、准备工作:安装 requests 库二、基本调用流程(以 RESTful API 为例)1.

在Linux系统上连接GitHub的方法步骤(适用2025年)

《在Linux系统上连接GitHub的方法步骤(适用2025年)》在2025年,使用Linux系统连接GitHub的推荐方式是通过SSH(SecureShell)协议进行身份验证,这种方式不仅安全,还... 目录步骤一:检查并安装 Git步骤二:生成 SSH 密钥步骤三:将 SSH 公钥添加到 github

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

PyCharm中配置PyQt的实现步骤

《PyCharm中配置PyQt的实现步骤》PyCharm是JetBrains推出的一款强大的PythonIDE,结合PyQt可以进行pythion高效开发桌面GUI应用程序,本文就来介绍一下PyCha... 目录1. 安装China编程PyQt1.PyQt 核心组件2. 基础 PyQt 应用程序结构3. 使用 Q

在macOS上安装jenv管理JDK版本的详细步骤

《在macOS上安装jenv管理JDK版本的详细步骤》jEnv是一个命令行工具,正如它的官网所宣称的那样,它是来让你忘记怎么配置JAVA_HOME环境变量的神队友,:本文主要介绍在macOS上安装... 目录前言安装 jenv添加 JDK 版本到 jenv切换 JDK 版本总结前言China编程在开发 Java

Spring Boot Actuator应用监控与管理的详细步骤

《SpringBootActuator应用监控与管理的详细步骤》SpringBootActuator是SpringBoot的监控工具,提供健康检查、性能指标、日志管理等核心功能,支持自定义和扩展端... 目录一、 Spring Boot Actuator 概述二、 集成 Spring Boot Actuat

Go语言编译环境设置教程

《Go语言编译环境设置教程》Go语言支持高并发(goroutine)、自动垃圾回收,编译为跨平台二进制文件,云原生兼容且社区活跃,开发便捷,内置测试与vet工具辅助检测错误,依赖模块化管理,提升开发效... 目录Go语言优势下载 Go  配置编译环境配置 GOPROXYIDE 设置(VS Code)一些基本

Spring Boot配置和使用两个数据源的实现步骤

《SpringBoot配置和使用两个数据源的实现步骤》本文详解SpringBoot配置双数据源方法,包含配置文件设置、Bean创建、事务管理器配置及@Qualifier注解使用,强调主数据源标记、代... 目录Spring Boot配置和使用两个数据源技术背景实现步骤1. 配置数据源信息2. 创建数据源Be