vue组件间通信

组件通信常用方式

prop 、eventbus(事件总线)、vuex

自定义事件 (不常用)

1、边界情况:$parent 、$children、$root、$ref、provide/inject

2、非prop特性:$attrs、$listeners

组件间通信:

1、Prop — Vue.js

// 父传给子
// child
props: {msg :String}
// parent
<component msg='hello world!'>
// 子传给父
// child
this.$emit('eventName', params)
// parent
<component @eventName="eventName($event)">

2、事件总线

任意两个组件之间传递值常用事件总线或者是vuex的方式

Vue使用事件总线的方法

//  项目中引入在main.js中
import VueBus from 'vue-bus'
Vue.use(VueBus)
// 使用
this.$bus.emit('reAdd', params)
this.$bus.on('reAdd')

实现原理:

// 事件派发、监听和回调管理
class Bus{
    constructor(){
        this.callbacks = {}
    }
    $on(name, fn){
        this.callbacks[name] = this.callbacks[name] || []
        this.callbacks[name].push(fn)
    }
    $emit(name, args){
        if(this.callbacks[name]){
             this.callbacks[name].forEach(cb => cb(args))
        }
    }
}

// main.js
vue.prototype.$bus = new Bus()
// 使用
this.$bus.emit('reAdd', params)
this.$bus.on('reAdd')

3、Vuex 是什么? | Vuex

创建唯一的全局数据管理管理者store,通过它管理数据并通知组件状态变更

4、$parent/$root

兄弟组件之间通信可通过共同祖辈搭桥,$parent或$root

// brother1
this.$parent.$on('funcName',(msg)=>{})
// brother2
this.$parent.$emit('funcName', 'hello world!')

5、$children

父组件可以通过$children访问子组件实现父子组件通信(缺点:不能保证子元素顺序)

// 子组件中有一个方法

handleClose() {
    
}
// 父组件中方法
clickHandle(){
    this.$children[0].handleClose()
}

6、$attrs/$listeners

包含了父作用于中不作为prop被识别(且获取)的特性绑定(class和style除外),当一个组件没有声明任何prop时,这里会包含所有父作用域的绑定(class和style除外),并且可以通过v-bind="$attrs"传入内部组件

// 子组件 msg没有在props中声明
<span>{{$attrs.msg}}</span>

// 父组件
<component msg="hello world!"/>



// 子组件 点击按钮会调父组件的handleClick方法
<button v-on="$listeners">按钮</button>
// 父组件
<component @click="handleClick"/>


7、refs

获取子节点引用

// 子组件
submitForm(){

}
// 父组件
<search-form ref="form"/>
this.$refs.form.submitForm()

8、provide/inject

能够实现祖先和后代之间的传值

// 祖先
provide(){
    return {
        msg: 'hello world'
    }
}
// 后代
inject:[ 'msg' ]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值