vue 2コンポーネント間の値伝達

1767 ワード

vue 2バージョンのコンポーネント間の値伝達の簡単な統合:
  • 親コンポーネント=』サブコンポーネント:propsおよびrefs
  • - 
    props: { msg: String }
    //parent
    
    
    this.$ref.helloWorld.msg
    
  • 子コンポーネント=』親コンポーネント:カスタムイベント
  • //child
    this.$emit('send', msg)
    //parent
    
    
  • 兄弟コンポーネント:共通の祖先を介してp a r e n tまたはparentまたはparentまたはroot
  • をブリッジする
    // brother1 
    this.$parent.$on('foo', handle) 
    // brother2 
    this.$parent.$emit('foo')
    
  • 祖先=>子孫provide/inject
  • // ancestor 
    provide() { 
        return {
            msg: 'welcome'
        } 
    }
    // descendant 
    inject: ['msg']
    
  • 子孫=』祖先再帰はroot
  • に配布された.
    //     dispatch  ,             
    function dispatch(eventName, data) { 
        let parent = this.$parent 
        while (parent) { 
            //      $emit   
            parent.$emit(eventName,data) 
            //                         
            parent = parent.$parent 
        } 
    }
    //   ,HelloWorld.vue 
    

    {{ msg }}

    // App.vue this.$on('hello', this.sayHello)
  • 任意の2つのコンポーネント間のイベントバスと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を使うことができます