博客
关于我
vue学习笔记(十)路由
阅读量:435 次
发布时间:2019-03-06

本文共 1810 字,大约阅读时间需要 6 分钟。

Vue Router 组件通信与路由传参详解

Vue Router 组件通信与路由传参

在前文中,我们学习了Vue Router的基础知识和使用方法。本文将深入探讨Vue Router在组件间通信和路由参数传递方面的实际应用。


Vue Router 组件通信

在Vue.js应用中,组件间的通信是一个核心问题。通过Vue Router,我们可以在路由切换时,轻松地在组件间传递参数。以下是实现组件间通信的常用方法:

1. 创建事件总线(Bus)

首先,我们需要创建一个事件总线,用于实现组件间的通信。在src/assets目录下,创建一个新的文件bus.js

import Vue from 'vue'export default new Vue({  methods: {    emit: Vue.prototype.$emit  }})

或者更简单地:

let bus = new Vue()export default bus

2. 具体组件实现

BrotherComponent.vue中:

SisterComponent.vue中:

3. 路由注册

src/router目录下,创建test.js

import Vue from 'vue'import Router from 'vue-router'import Brother from '@/components/test04/BrotherComponent'import Sister from '@/components/test04/SisterComponent'Vue.use(Router)export default new Router({  routes: [    {      path: '/',      name: 'Brother',      component: Brother    },    {      path: '/sister',      name: 'Sister',      component: Sister    }  ]})

Vue Router 路由参数传递

在Vue Router中,路由参数的传递是实现组件间通信的重要手段。以下是两种常用方式:paramsquery

1. params 参数传递

发送参数

在组件中使用$router.push方法:

methods: {  sendMsg() {    this.$router.push({      name: 'two',      params: {        code: this.code      }    })  }}

接收参数

在目标组件中使用$route.params

2. query 查询参数

发送参数

在组件中使用$router.push方法:

methods: {  sendMsg() {    this.$router.push({      path: 'Four',      query: {        msg: this.msg      }    })  }}

接收参数

在目标组件中使用$route.query


params 和 query 的区别

特性 params query
URL 中的表现 没有显示 显示在地址栏
数据持久性 不持久 持久
数据传递方式 只能通过 name 可以通过 path 或 name
数据在组件中的获取 $route.params $route.query

总结

通过上述方法,我们可以轻松实现组件间的通信和路由参数的传递。在实际开发中,可以根据具体需求选择合适的传递方式,灵活配置路由参数,提升应用的功能和用户体验。

转载地址:http://fsfyz.baihongyu.com/

你可能感兴趣的文章
SpringBoot为什么易学难精?
查看>>
poj 2545 Hamming Problem
查看>>
poj 2723
查看>>
poj 2763 Housewife Wind
查看>>
Qt笔记——模型/视图MVD 文件目录浏览器软件
查看>>
POJ 2892 Tunnel Warfare(树状数组+二分)
查看>>
poj 2965 The Pilots Brothers' refrigerator-1
查看>>
poj 3026( Borg Maze BFS + Prim)
查看>>
POJ 3041 - 最大二分匹配
查看>>
POJ 3041 Asteroids(二分匹配模板题)
查看>>
Qt笔记——标准文件对话框QFileDialog
查看>>
poj 3083 Children of the Candy Corn
查看>>
POJ 3083 Children of the Candy Corn 解题报告
查看>>
POJ 3253 Fence Repair C++ STL multiset 可解 (同51nod 1117 聪明的木匠)
查看>>
Qt笔记——控件总结
查看>>
poj 3262 Protecting the Flowers 贪心
查看>>
poj 3264(简单线段树)
查看>>
Qt笔记——布局管理三件套分割窗口、停靠窗口和堆栈窗口
查看>>
poj 3277 线段树
查看>>
POJ 3349 Snowflake Snow Snowflakes
查看>>