vue2.0組件通信各種情況總結與實例分析


Props在vue組件中各種角色總結

在Vue中組件是實現模塊化開發的主要內容,而組件的通信更是vue數據驅動的靈魂,現就四種主要情況總結如下:

使用props傳遞數據---組件內部

//html
<div id="app1">
    <i>注意命名規定:僅在html內使用my-message</i>
    <child my-message="組件內部數據傳遞"></child>
</div>
//js
<script>
    Vue.component('child', {
        props: ['myMessage'],
        template: '<mark>{{ myMessage }}<mark/>'
    });
    new Vue({
        el: '#app1'
    })
</script>

動態props通信---組件與根節點(父子之間)

<div id="app2">
    <input v-model="parentMsg">
    <br>
    <child :parent-msg="parentMsg"></child>
</div>
<script>
    Vue.component('child', {
        props: ['parentMsg'],
        template: '<mark>{{ parentMsg }}<mark/>'
    });
    new Vue({
        el: '#app2',
        data: {
            parentMsg: 'msg from parent!'
        }
    })
</script>
  • 對比分析:
  • 例子1:
<comp some-prop="1"></comp>
//組件內部數據傳遞,對應字面量語法:傳遞了一個字符串"1" 
  • 例子2:
<comp v-bind:some-prop="1"></comp>
//組件與根節點數據傳遞,對應動態語法:傳遞實際的數字:js表達式 

單向數據流動特點:父組件屬性變化時將傳導給子組件,反之不可

  • 兩種改變prop情況
  • 注意在 JavaScript 中對象和數組是引用類型,指向同一個內存空間,如果 prop 是一個對象或數組,在子組件內部改變它會影響父組件的狀態。
//定義一個局部data屬性,並將 prop 的初始值作為局部數據的初始值
props: ['initialCounter'],
            data: function () {
            return { counter: this.initialCounter }
            }
//定義一個局部computed屬性,此屬性從 prop 的值計算得出
 props: ['size'],
            computed: {
            normalizedSize: function () {
            return this.size.trim().toLowerCase()
            }
            }

子組件索引

盡管有 props 和 events ,但是有時仍然需要在 JavaScript 中直接訪問子組件。為此可以使用 ref 為子組件指定一個索引 ID

<div id="parent">
    <!-- vm.$refs.p will be the DOM node -->
    <b ref="p">hello</b>
    <!-- vm.$refs.child will be the child comp instance -->
    <user-profile v-for='i in 3' ref="profile"></user-profile>
</div>
<script>
    var userPf=Vue.component('user-profile',{
        template:'<div>hello $refs</div>'
    });
    var parent = new Vue({ el: '#parent' });
    // 訪問子組件
    var child = parent.$refs.profile;
    console.log(child[0]);
    console.log(parent.$refs.p);
</script>

$refs 只在組件渲染完成后才填充,並且它是非響應式的。它僅僅作為一個直接訪問子組件的應急方案——應當避免在模版或計算屬性中使用 $refs 。

數據反傳---自定義事件

自定義事件的根基在於每個vue實例都實現了事件接口(Event interface)
Vue的事件系統分離自瀏覽器的EventTarget API。盡管它們的運行類似,但是$on 和 $emit 不是addEventListener 和 dispatchEvent 的別名。
父組件可以在使用子組件的地方直接用 v-on 來監聽子組件觸發的事件

  • 監聽:$on(eventName)
  • 觸發:$emit(eventName)
<div id="app3">
    <p>Look at the parent's data: <mark>{{t}}</mark> & the child's data: <mark>{{childWords}}</mark></p>
    <child v-on:add="pChange"></child>
    <child v-on:add="pChange"></child>
    <child v-on:click.native="native"></child>
</div>
<script>
    Vue.component('child', {
        template: `<button @click="add">{{ c }}</button>`,
        data: function () {
            return {
                c: 0,
                msg: 'I am from child\'s data'
            }
        },
        methods: {
            add: function () {
                this.c += 1;
                this.$emit('add',this.msg);
            }
        },
    });
    new Vue({
        el: '#app3',
        data: {
            t: 0,
            childWords: ''
        },
        methods: {
            pChange: function (msg) {
                this.t += 1;
                this.childWords=msg;
            },
            native:function () {
                alert('I am a native event ,which comes from the root element!');
            }
        }
    })
</script>

兄弟間通信---簡單場景用bus,復雜場景用vuex

<div id="app4">
    <display></display>
    <increment></increment>
</div>
<script>
    var bus = new Vue();
    Vue.component('increment', {
        template: `<button @click="add">+</button>`,
        data: function () {
            return {count: 0}
        },
        methods: {
            add: function () {
                bus.$emit('inc', this.count+=1)
            }
        }
    });
    Vue.component('display', {
        template: `<span>Clicked: <mark>{{c}}</mark> times</span>`,
        data: function () {
            return {c: 0}
        },
        created: function () {
            var self=this;
//            bus.$on('inc', function (num) {
//                self.c = num
//            });
            bus.$on('inc',  (num) =>
                this.c = num
            );
        }
    });
    vm = new Vue({
        el: "#app4",
    })
</script>

總結:Vue中關於組件間及組件與根節點間通信都可以人為是父子兄弟間的通信,另外父子關系是相對的即與上下文有關(比如A組件的父組件可能是B組件的子組件);上述四個例子分別演示了不同組件通信的機制。
澄清了上述問題不難理這句話:
編譯作用域---父組件模板的內容在父組件作用域內編譯;子組件模板的內容在子組件作用域內編譯。分發內容是在父組件作用域內編譯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM