兄弟组件通信
A组件要传递数据给B组件 A组件是有数据的, B组件是需要数据的
-
vue的各个组件data是不共享的,但是我们有时需要传递数据,那么就可以使用vuex的store, store是一个对象,里面有个state,用来存储多个组件需要使用的数据
-
我们先定义数据 在store的state中, 定义数据
-
然后 在store的 mutations 中 ,定义方法 fn
-
在 A组件中,调用方法 this.$store.commit(‘playbackHistory’, icao)
”playbackHistory“ 是 方法 fn (在mutations中,定义的方法名称)
icao 是要传递的数据 -
在B组件中可以接受数据 this.$store.state.icao
ps:不建议直接修改this.$store.state的数据,因为严格模式时,会报错
子向父传递
- 子组件中发出消息
clickBtn(){
// 子组件发出消息
this.$emit('alone', arguments);
},
alone是父组件中的事件, arguments 是子组件要传给父组件的数据
- 父组件接受 数据 在父组件中
<template>
<Son @alone="alone"></Son>
</template>
<script>
methods() {
alone (aa) {
console.log( ' 子组件触发的我 ' )
console.log( ' 子组件传给我的数据是 ' , aa )
}
}
</script>
父组件向子组件
- 父组件中
<template>
<Son :info="infoPopInfo"></Son>
// infoPopInfo 是父组件中的数据
</template>
2.子组件中
<script>
export default {
props:['info'],
// info 可以直接在子组件中使用,用法和在data 中定义的一样
}
</script>