怎樣在 Vue 里面使用自定義事件將子組件的數據傳回給父組件?


首先, Vue 里面的組件之間的數據流動是 單向 的, 數據可以從父組件傳遞給子組件, 但不能從子組件傳遞給父組件, 因為組件和組件之間是 隔離 的. 就像兩個嵌套的 黑盒子 .

能通過 props 向子組件傳遞數據其實是因為子組件 暴露 出了這個屬性到 外部, 但子組件並不知道是誰把數據傳過來的.

要把數據傳回給父組件, 那就需要 自定義事件, 這相當於是給子組件安了一個 監視器 , 使得父組件可以 監測 到子組件的一舉一動, 這樣也就可以拿到子組件的數據了.

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
    <title>Vue Test</title>
</head>

<body>
    <div id="app">
        <div id="counter-event-example">
            <p>{{ total }}</p>
            <!-- 父組件綁定子組件的自定義事件: increment -->
            <button-counter v-on:increment="incrementTotal"></button-counter>
            <button-counter v-on:increment="incrementTotal"></button-counter>
        </div>
    </div>

    <script>
        Vue.component('button-counter', {
            template: '<button v-on:click="incrementHandler">{{ counter }}</button>',
            // 這里的 data 不是一個對象, 而是一個可以返回一個對象的函數
            // 好處是每個實例可維護一份被返回對象的獨立拷貝,若 data 為對象則會影響其他實例
            data: function () {
                return {
                    counter: 0
                }
            },
            methods: {
                incrementHandler: function () {
                    this.counter += 1;
                    // $emit() 可將 調用當前方法的事件 外拋, 實現 自定義事件.
                    this.$emit('increment');
                }
            },
        })
        new Vue({
            el: '#counter-event-example',
            data: {
                total: 0
            },
            methods: {
                incrementTotal: function () {
                    this.total += 1
                }
            }
        })
    </script>
</body>

</html>

 


免責聲明!

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



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