Vue 구성요소 간에 통신하는 방법은 무엇입니까? 방법 소개

青灯夜游
풀어 주다: 2020-10-26 17:54:45
앞으로
2180명이 탐색했습니다.

Vue 구성요소 간에 통신하는 방법은 무엇입니까? 방법 소개

구성 요소 통신

자식 구성 요소는 this.$parent를 사용하여 상위 구성 요소와 상위 체인의 모든 인스턴스에 액세스할 수 있지만 하위 구성 요소는 상위 구성 요소의 데이터에 직접 의존하는 것을 피하고 다음을 시도해야 합니다. 명시적으로 소품을 사용하여 데이터를 전달합니다.

또한 다음과 같은 이유로 하위 구성 요소에서 상위 구성 요소의 상태를 수정하는 것은 매우 나쁜 습관입니다.

  • 이로 인해 상위 구성 요소와 하위 구성 요소가 긴밀하게 결합됩니다.

  • 이해하기 어렵습니다. 상태를 확인해야만 상위 구성요소를 확인할 수 있습니다. 하위 구성 요소에 의해 수정될 수 있기 때문입니다! 이상적으로는 구성 요소 자체만 상태를 수정할 수 있습니다.

각 Vue 인스턴스는 이벤트 트리거입니다.

  • $on() - 이벤트를 수신합니다.

  • $emit() - 범위 체인 위로 이벤트를 전달합니다. (트리거 이벤트)

  • $dispatch() - 상위 체인을 따라 버블링되는 이벤트를 전달합니다.

  • $broadcast() - 이벤트를 방송하고 모든 후손에게 이벤트를 전파합니다.

Listening and Triggering

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 이벤트 - $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. 하위 구성 요소의 버튼 요소는 알림 메서드를 가리키는 클릭 이벤트에 바인딩됩니다.

  2. 하위 구성 요소가 처리되고, $dispatch가 호출되고, 이벤트가 상위 구성 요소의 child-msg 이벤트로 전달되고, msg 매개 변수가 이벤트에 제공됩니다

  3. 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>This is child component 1</h2>
        </template>
        
        <template id="child-component2">
            <h2>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>This is child component 1</h2>
        </template>
        
        <template id="child-component2">
            <h2>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>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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:cnblogs.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!