vue 2 组件之间传值

对vue2版本的组件之间传值的一个简单整合:

  1. 父组件 =》 子组件: props 和 refs
- 
props: { msg: String }
//parent
<hello-world :msg="welcome to vue.js" />

this.$ref.helloWorld.msg
  1. 子组件 =》 父组件 : 自定义事件
//child
this.$emit('send', msg)
//parent
<hello-world @send="sendMsg($event)" />
  1. 兄弟组件: 通过共同祖辈搭桥 p a r e n t 或 parent或 parentroot
// brother1 
this.$parent.$on('foo', handle) 
// brother2 
this.$parent.$emit('foo')
  1. 祖先=>后代 provide/inject
// ancestor 
provide() { 
    return {
        msg: 'welcome'
    } 
}
// descendant 
inject: ['msg']
  1. 后代 =》祖先 递归一直派发到root
// 定义一个dispatch方法,指定要派发事件名称和数据 
function dispatch(eventName, data) { 
    let parent = this.$parent 
    while (parent) { 
        // 父元素来用$emit触发 
        parent.$emit(eventName,data) 
        // 递归查找父元素  只要还存在父元素就继续往上查找
        parent = parent.$parent 
    } 
}
// 使用,HelloWorld.vue 
<h1 @click="dispatch('hello', 'hello,world')">{{ msg }}</h1> 
// App.vue 
this.$on('hello', this.sayHello)
  1. 任意两个组件之间 事件总线 和 vuex

    事件总线

class EventBus {
    constructor() {
        this.callbacks = {}
    }
    $on(name, fn) {
        this.callbacks[name] = this.callbacks[name] || []
        this.callbacks[name].push(fn)
    }
    $emit(name) {
        let fns = this.callbacks[name]
        if(fns) {
            fns.map(fn => fn())
        }
    }
}

//运用

main.js

Vue.prototype.$bus = new EventBus()

this.$bus.$on('send', handleFn)
this.$bus.$emit('send')

vuex: 创建唯一的全局数据管理者store,过载到vue实例,通过它管理状态数据并通知组件状态变更

3,4,5,6 都可以直接用$root

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值