vue兄弟组件间的数据传递
一、路由URL参数
1.在传统开发时我们常常把需要跨页面传递的数据放到url后面,跳转到另外页面时直接获取url字符串获取想要的参数即可
// router index.js 动态路由
{
path:'/params/:Id',
component:Params,
name:Params
}
2 跳转路由
// 跳转路由
<router-link :to="/params/12">跳转路由</router-link>
二、Bus通信
1.在组件之外定义一个bus.js作为组件间通信的桥梁,适用于比较小型不需要vuex又需要兄弟组件通信的
bus.js中添加如下
import Vue from 'vue'
export default new Vue
2.组件中调用bus.js通过自定义事件传递数据
import Bus from './bus.js'
export default {
methods: {
bus () {
Bus.$emit('msg', '我要传给兄弟组件们')
}
}
}
3 兄弟组件中监听事件接受数据
import Bus from './bus.js'
export default {
mounted() {
Bus.$on('msg', (e) => {
console.log(e)
})
}
}