搜尋
首頁web前端Vue.jsvue組件間如何進行通訊?方法介紹

vue組件間如何進行通訊?方法介紹

Oct 26, 2020 pm 05:54 PM
vue組件通信

vue組件間如何進行通訊?方法介紹

元件通訊

儘管子元件可以用this.$parent存取它的父元件及其父鏈上任意的實例,不過子元件應避免直接依賴父元件的數據,盡量明確地使用 props 傳遞資料。

另外,在子元件中修改父元件的狀態是非常糟糕的做法,因為: 

  • 這讓父元件與子元件緊密耦合; 

  • 只看父元件,很難理解父元件的狀態。因為它可能被任意子組件修改!理想情況下,只有組件自己能修改它的狀態。

每個Vue實例都是事件觸發器:

  • $on()-監聽事件。

  • $emit()-把事件沿著作用域鏈往上派送。 (觸發事件)

  • $dispatch()-派發事件,事件沿著父鏈冒泡。

  • $broadcast()-廣播事件,事件向下傳導給所有的後代。

監聽與觸發

v-on監聽自訂事件:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <!--子组件模板-->
        <template id="child-template">
            <input v-model="msg" />
            <button v-on:click="notify">Dispatch Event</button>
        </template>
        <!--父组件模板-->
        <div id="events-example">
            <p>Messages: {{ messages | json }}</p>
            <child v-on:child-msg="handleIt"></child>
        </div>
    </body>
    <script src="js/vue.js"></script>
    <script>
//        注册子组件
//        将当前消息派发出去
        Vue.component(&#39;child&#39;, {
            template: &#39;#child-template&#39;,
            data: function (){
                return { msg: &#39;hello&#39; }
            },
            methods: {
                notify: function() {
                    if(this.msg.trim()){
                        this.$dispatch(&#39;child-msg&#39;,this.msg);
                        this.msg = &#39;&#39;;
                    }
                }
            }
        })
//        初始化父组件
//        在收到消息时将事件推入一个数组中
        var parent = new Vue({
            el: &#39;#events-example&#39;,
            data: {
                messages: []
            },
            methods:{
                &#39;handleIt&#39;: function(){
                    alert("a");
                }
            }
        })
    </script>
</html>

vue組件間如何進行通訊?方法介紹

父元件可以在使用子元件的地方直接用 v-on 來監聽子元件觸發的事件:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="counter-event-example">
          <p>{{ total }}</p>
          <button-counter v-on:increment="incrementTotal"></button-counter>
          <button-counter v-on:increment="incrementTotal"></button-counter>
        </div>
    </body>
    <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">
        Vue.component(&#39;button-counter&#39;, {
          template: &#39;<button v-on:click="increment">{{ counter }}</button>&#39;,
          data: function () {
            return {
              counter: 0
            }
          },
          methods: {
            increment: function () {
              this.counter += 1
              this.$emit(&#39;increment&#39;)
            }
          },
        })
        new Vue({
          el: &#39;#counter-event-example&#39;,
          data: {
            total: 0
          },
          methods: {
            incrementTotal: function () {
              this.total += 1
            }
          }
        })
    </script>
</html>

vue組件間如何進行通訊?方法介紹

在某個元件的根元素上監聽一個原生事件。可以使用 .native 修飾v-on 。例如:

<my-component v-on:click.native="doTheThing"></my-component>

派發事件-$dispatch()

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <p>Messages: {{ messages | json }}</p>
            <child-component></child-component>
        </div>
        <template id="child-component">
            <input v-model="msg" />
            <button v-on:click="notify">Dispatch Event</button>
        </template>

    <script src="js/vue.js"></script>
    <script>
        // 注册子组件
        Vue.component(&#39;child-component&#39;, {
            template: &#39;#child-component&#39;,
            data: function() {
                return {
                    msg: &#39;&#39;
                }
            },
            methods: {
                notify: function() {
                    if (this.msg.trim()) {
                        this.$dispatch(&#39;child-msg&#39;, this.msg)
                        this.msg = &#39;&#39;
                    }
                }
            }
        })
    
        // 初始化父组件
        new Vue({
            el: &#39;#app&#39;,
            data: {
                messages: []
            },
            events: {
                &#39;child-msg&#39;: function(msg) {
                    this.messages.push(msg)
                }
            }
        })
    </script>
    </body>
</html>

vue組件間如何進行通訊?方法介紹

  1. #子元件的button元素綁定了click事件,該事件指向notify方法

  2. 子元件的notify方法在處理時,呼叫了$dispatch,將事件派發到父元件的child-msg事件,並給該事件提供了一個msg參數

  3. 父元件的events選項中定義了child-msg事件,父元件接收到子元件的派發後,呼叫child-msg事件。

廣播事件-$broadcast()

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <input v-model="msg" />
            <button v-on:click="notify">Broadcast Event</button>
            <child-component></child-component>
        </div>
        
        <template id="child-component">
            <ul>
                <li v-for="item in messages">
                    父组件录入了信息:{{ item }}
                </li>
            </ul>
        </template>

    <script src="js/vue.js"></script>
    <script>
        // 注册子组件
        Vue.component(&#39;child-component&#39;, {
            template: &#39;#child-component&#39;,
            data: function() {
                return {
                    messages: []
                }
            },
            events: {
                &#39;parent-msg&#39;: function(msg) {
                    this.messages.push(msg)
                }
            }
        })
        // 初始化父组件
        new Vue({
            el: &#39;#app&#39;,
            data: {
                msg: &#39;&#39;
            },
            methods: {
                notify: function() {
                    if (this.msg.trim()) {
                        this.$broadcast(&#39;parent-msg&#39;, this.msg)
                    }
                }
            }
        })
    </script>
    </body>
</html>

和派發事件相反。前者在子元件綁定,呼叫$dispatch派發到父元件;後者在父元件中綁定,呼叫$broadcast廣播到子元件。

父子元件之間的存取

  • 父元件存取子元件:使用$children或$refs

  • #子元件存取父元件:使用$parent

  • 子元件存取根元件:使用$root

$children:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <parent-component></parent-component>
        </div>
        
        <template id="parent-component">
            <child-component1></child-component1>
            <child-component2></child-component2>
            <button v-on:click="showChildComponentData">显示子组件的数据</button>
        </template>
        
        <template id="child-component1">
            <h2 id="This-nbsp-is-nbsp-child-nbsp-component-nbsp">This is child component 1</h2>
        </template>
        
        <template id="child-component2">
            <h2 id="This-nbsp-is-nbsp-child-nbsp-component-nbsp">This is child component 2</h2>
        </template>
        <script src="js/vue.js"></script>
        <script>
            Vue.component(&#39;parent-component&#39;, {
                template: &#39;#parent-component&#39;,
                components: {
                    &#39;child-component1&#39;: {
                        template: &#39;#child-component1&#39;,
                        data: function() {
                            return {
                                msg: &#39;child component 111111&#39;
                            }
                        }
                    },
                    &#39;child-component2&#39;: {
                        template: &#39;#child-component2&#39;,
                        data: function() {
                            return {
                                msg: &#39;child component 222222&#39;
                            }
                        }
                    }
                },
                methods: {
                    showChildComponentData: function() {
                        for (var i = 0; i < this.$children.length; i++) {
                            alert(this.$children[i].msg)
                        }
                    }
                }
            })
        
            new Vue({
                el: &#39;#app&#39;
            })
        </script>
    </body>
</html>

vue組件間如何進行通訊?方法介紹

$ref可以給子元件指定索引ID:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <parent-component></parent-component>
        </div>
        
        <template id="parent-component">
            <!--<child-component1></child-component1>
            <child-component2></child-component2>-->
            <child-component1 v-ref:cc1></child-component1>
            <child-component2 v-ref:cc2></child-component2>
            <button v-on:click="showChildComponentData">显示子组件的数据</button>
        </template>
        
        <template id="child-component1">
            <h2 id="This-nbsp-is-nbsp-child-nbsp-component-nbsp">This is child component 1</h2>
        </template>
        
        <template id="child-component2">
            <h2 id="This-nbsp-is-nbsp-child-nbsp-component-nbsp">This is child component 2</h2>
        </template>
        <script src="js/vue.js"></script>
        <script>
            Vue.component(&#39;parent-component&#39;, {
                template: &#39;#parent-component&#39;,
                components: {
                    &#39;child-component1&#39;: {
                        template: &#39;#child-component1&#39;,
                        data: function() {
                            return {
                                msg: &#39;child component 111111&#39;
                            }
                        }
                    },
                    &#39;child-component2&#39;: {
                        template: &#39;#child-component2&#39;,
                        data: function() {
                            return {
                                msg: &#39;child component 222222&#39;
                            }
                        }
                    }
                },
                methods: {
                    showChildComponentData: function() {
//                        for (var i = 0; i < this.$children.length; i++) {
//                            alert(this.$children[i].msg)
//                        }
                        alert(this.$refs.cc1.msg);
                        alert(this.$refs.cc2.msg);
                    }
                }
            })
            new Vue({
                el: &#39;#app&#39;
            })
        </script>
    </body>
</html>

效果與$children相同。

$parent:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <parent-component></parent-component>
        </div>
        
        <template id="parent-component">
            <child-component></child-component>
        </template>
        
        <template id="child-component">
            <h2 id="This-nbsp-is-nbsp-a-nbsp-child-nbsp-component">This is a child component</h2>
            <button v-on:click="showParentComponentData">显示父组件的数据</button>
        </template>
        
        <script src="js/vue.js"></script>
        <script>
            Vue.component(&#39;parent-component&#39;, {
                template: &#39;#parent-component&#39;,
                components: {
                    &#39;child-component&#39;: {
                        template: &#39;#child-component&#39;,
                        methods: {
                            showParentComponentData: function() {
                                alert(this.$parent.msg)
                            }
                        }
                    }
                },
                data: function() {
                    return {
                        msg: &#39;parent component message&#39;
                    }
                }
            })
            new Vue({
                el: &#39;#app&#39;
            })
        </script>
    </body>
</html>

vue組件間如何進行通訊?方法介紹

如開篇所提,不建議在子元件中修改父元件的狀態。

 非父子元件溝通

有時候非父子關係的元件也需要溝通。在簡單的場景下,使用一個空的Vue 實例作為中央事件總線:

var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit(&#39;id-selected&#39;, 1)
// 在组件 B 创建的钩子中监听事件
bus.$on(&#39;id-selected&#39;, function (id) {
    // ...
})

#相關推薦:

2020年前端vue面試題大匯總(附答案)

vue教學推薦:2020最新的5個vue.js影片教學精選

更多程式相關知識,請訪問:程式設計入門! !

以上是vue組件間如何進行通訊?方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:博客园。如有侵權,請聯絡admin@php.cn刪除
vue.js的功能:增強前端的用戶體驗vue.js的功能:增強前端的用戶體驗Apr 19, 2025 am 12:13 AM

Vue.js通過多種功能提升用戶體驗:1.響應式系統實現數據即時反饋;2.組件化開發提高代碼復用性;3.VueRouter提供平滑導航;4.動態數據綁定和過渡動畫增強交互效果;5.錯誤處理機制確保用戶反饋;6.性能優化和最佳實踐提升應用性能。

vue.js:定義其在網絡開發中的作用vue.js:定義其在網絡開發中的作用Apr 18, 2025 am 12:07 AM

Vue.js在Web開發中的角色是作為一個漸進式JavaScript框架,簡化開發過程並提高效率。 1)它通過響應式數據綁定和組件化開發,使開發者能專注於業務邏輯。 2)Vue.js的工作原理依賴於響應式系統和虛擬DOM,優化性能。 3)實際項目中,使用Vuex管理全局狀態和優化數據響應性是常見實踐。

了解vue.js:主要是前端框架了解vue.js:主要是前端框架Apr 17, 2025 am 12:20 AM

Vue.js是由尤雨溪在2014年發布的漸進式JavaScript框架,用於構建用戶界面。它的核心優勢包括:1.響應式數據綁定,數據變化自動更新視圖;2.組件化開發,UI可拆分為獨立、可複用的組件。

Netflix的前端:React(或VUE)的示例和應用Netflix的前端:React(或VUE)的示例和應用Apr 16, 2025 am 12:08 AM

Netflix使用React作為其前端框架。 1)React的組件化開發模式和強大生態系統是Netflix選擇它的主要原因。 2)通過組件化,Netflix將復雜界面拆分成可管理的小塊,如視頻播放器、推薦列表和用戶評論。 3)React的虛擬DOM和組件生命週期優化了渲染效率和用戶交互管理。

前端景觀:Netflix如何處理其選擇前端景觀:Netflix如何處理其選擇Apr 15, 2025 am 12:13 AM

Netflix在前端技術上的選擇主要集中在性能優化、可擴展性和用戶體驗三個方面。 1.性能優化:Netflix選擇React作為主要框架,並開發了SpeedCurve和Boomerang等工具來監控和優化用戶體驗。 2.可擴展性:他們採用微前端架構,將應用拆分為獨立模塊,提高開發效率和系統擴展性。 3.用戶體驗:Netflix使用Material-UI組件庫,通過A/B測試和用戶反饋不斷優化界面,確保一致性和美觀性。

React與Vue:Netflix使用哪個框架?React與Vue:Netflix使用哪個框架?Apr 14, 2025 am 12:19 AM

NetflixusesAcustomFrameworkcalled“ Gibbon” BuiltonReact,notReactorVuedIrectly.1)TeamSperience:selectBasedonFamiliarity.2)ProjectComplexity:vueforsimplerprojects:reactforforforproproject,reactforforforcompleplexones.3)cocatizationneedneeds:reactoffipicatizationneedneedneedneedneedneeds:reactoffersizationneedneedneedneedneeds:reactoffersizatization needefersmoreflexibleise.4)

框架的選擇:是什麼推動了Netflix的決定?框架的選擇:是什麼推動了Netflix的決定?Apr 13, 2025 am 12:05 AM

Netflix在框架選擇上主要考慮性能、可擴展性、開發效率、生態系統、技術債務和維護成本。 1.性能與可擴展性:選擇Java和SpringBoot以高效處理海量數據和高並發請求。 2.開發效率與生態系統:使用React提升前端開發效率,利用其豐富的生態系統。 3.技術債務與維護成本:選擇Node.js構建微服務,降低維護成本和技術債務。

反應,vue和Netflix前端的未來反應,vue和Netflix前端的未來Apr 12, 2025 am 12:12 AM

Netflix主要使用React作為前端框架,輔以Vue用於特定功能。 1)React的組件化和虛擬DOM提升了Netflix應用的性能和開發效率。 2)Vue在Netflix的內部工具和小型項目中應用,其靈活性和易用性是關鍵。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具