组件之间的通信主要有父子组件间的通信和兄弟组件间的通信,最近练手项目中有用到,记录下来备忘
父子组件通信
父组件向子组件共享数据可以使用自定属性props:["属性名"]
,子组件可以通过自定义事件来将数据发送给父组件。利用自定义属性和自定义事件可以很方便的实现父子通信。
- 修改数据时,子组件中通过this.$emit(‘函数名’,传递的值)来触发自定义事件
- 父组件中使用@ 绑定事件,子组件向父组件传递的数据通过val接收
兄弟组件通信
利用父组件作为中间件
简单的兄弟组件的通信,最简单粗暴的办法的办法就是利用两次父子通信来实现兄弟间的通信,子组件1通过$emit将数据发送给父组件,父组件再通过自定义属性将接收到的数据传给子组件2.
使用EventBus
使用步骤
- 创建eventBus.js模块,并向外共享一个Vue的实例对象(或者定义一个新的bus对象并且挂载在原型链上)
Vue.prototype.$bus = new Vue()
- 在数据发送方,调用bus.$emit(‘事件名称’,要发送的数据)触发自定义事件
this.$bus.$emit('getDetail', id)
- 在数据接收方,调用bus.$on(‘事件名称’,事件处理函数)注册一个自定义事件
created () {
this.$bus.$on('getDetail', res => {
this.goodsId = res
console.log(res)
})
}
使用VueX
- 安装插件:
npm i vuex --save
- 创建store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
queryId: '',
},
mutations:{
store_queryId(state, queryId) {
state.queryId = queryId
}
}
})
- 在main.js中引入并向外共享实例
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
- 数据发送方
this.$store.commit("store_queryId",queryId)
- 数据接收方
let queryId = this.$store.state.queryId;