项目中,代理商详细查询需要传入一个item.id给兄弟组件作为调用API的参数,这里就涉及到了非父子传值。

目前我接触的一共有以下几种方式。

1.利用vue总线注册公共组件传值

如图所示,我们可以创建一个公共的总线,通过它来传递。具体代码如下:

1
2
3
4
5
//创立bus.js

import Vue from 'vue'
const Bus = new Vue()
export default Bus

在组件A中把调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Bus from './Bus'

export default {
data() {
return {
.........
}
},
methods: {
....
Bus.$emit('log', 120) //把要发送的数据挂载到bus上
},

}

在组件B中调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Bus from './Bus'

export default {
data() {
return {
.........
}
},
mounted () {
Bus.$on('log', content => {
console.log(content) //把监听到的内容获取为自己所用
});
}
}

传值成功。

2.利用$router路由传参

这种是要有一定的巧合,需要满足在路由链上,刚好路由过去的组件是需要当前组件的数据。

我们可以通过其挂载。

1
2
3
4
5
6
7
8
9
10
11
12
//携带agentCode跳转到agentDetail组件
//这里的item是该函数接收的形参值

goDetail(item) {
this.$router.push({
path: '/agentDetail',
query: {
agentCode: item.agentCode
}
});
},

angentDetail组件中,我们需要接收到路由过来的值。当我们点击路由时,会通过地址栏传过去。

1
2
3
4
5
//通过生命周期函数把传过来的参数获取 
created() {
this.agentCode = this.$route.query.agentCode;//注意,这里是$route
},

当然,query可以携带更多的参数,但是超过一定限制不建议这么做。

3.利用vuex传参

这个是vue官方存储库,相对于利用vue原型注册的$bus这种总线传参方式,vuex中store不仅仅用来作为存储,它有着更为强大的处理能力,例如通过调用其中的方法getters\mutations等处理数据。

我们这里使用官方演示的demo。

如图,我们可以在任何组件中,通过this.$store.commit调用vuex中mutations定义的函数,从而获取到store中的值。

vuex可以玩性很多,如果只是单一传值,个人认为总线方式更好。

4.利用sessionStorage传值

是的,我们可以使用它,因为目前接触到的应用一般都是SPA(single page web application,单页富应用程序)应用,不存在跨域问题,该方法可行性是存在的。

我们先编写一段代码测试:

1
2
3
4
5
6
7
8
//home
<button @click="setstor">把值存入sessionstorage</button>
.......
methods:{
setstor() {
sessionStorage.setItem("testKey", "这是一个测试的value值");
},
}
1
2
3
4
5
6
7
8
9
//about
<button @click="getsession">点击按钮显示</button> {{ datas }}
........
methods: {
getsession() {
this.datas = sessionStorage.getItem("testKey");
},
},

最终演示效果如图所示:

看来sessionStorage是可以的。同理,理论上localStorage也可以,只不过需要清理罢了,防止数据污染。

写在最后

以上,是我在开发学习中使用到的方法,当然,这里面有一些方法还需要一起探讨,例如最后利用sessionStorage我并没有在项目中看到过,如果你有更好的方法,欢迎在评论区提出。