찾다
웹 프론트엔드View.jsVue 구성요소 간에 통신하는 방법은 무엇입니까? 방법 소개

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 ></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 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으로 문의하시기 바랍니다. 삭제
Netflix의 프론트 엔드의 반응, vue 및 미래Netflix의 프론트 엔드의 반응, vue 및 미래Apr 12, 2025 am 12:12 AM

Netflix는 주로 VUE가 특정 기능을 위해 보충하는 프론트 엔드 프레임 워크로 React를 사용합니다. 1) React의 구성 요소화 및 가상 DOM은 Netflix 애플리케이션의 성능 및 개발 효율을 향상시킵니다. 2) VUE는 Netflix의 내부 도구 및 소규모 프로젝트에 사용되며 유연성과 사용 편의성이 핵심입니다.

프론트 엔드의 vue.js : 실제 응용 프로그램 및 예제프론트 엔드의 vue.js : 실제 응용 프로그램 및 예제Apr 11, 2025 am 12:12 AM

vue.js는 복잡한 사용자 인터페이스를 구축하는 데 적합한 점진적인 JavaScript 프레임 워크입니다. 1) 핵심 개념에는 반응 형 데이터, 구성 요소화 및 가상 DOM이 포함됩니다. 2) 실제 응용 분야에서는 TODO 응용 프로그램을 구축하고 Vuerouter를 통합하여 시연 할 수 있습니다. 3) 디버깅 할 때 VuedeVtools 및 Console.log를 사용하는 것이 좋습니다. 4) 성능 최적화는 V-IF/V- 쇼, 목록 렌더링 최적화, 구성 요소의 비동기로드 등을 통해 달성 할 수 있습니다.

vue.js and React : 주요 차이점 이해vue.js and React : 주요 차이점 이해Apr 10, 2025 am 09:26 AM

vue.js는 중소형 프로젝트에 적합하지만 REACT는 크고 복잡한 응용 프로그램에 더 적합합니다. 1. Vue.js의 응답 형 시스템은 종속성 추적을 통해 DOM을 자동으로 업데이트하여 데이터 변경을 쉽게 관리 할 수 ​​있습니다. 2. 반응은 단방향 데이터 흐름을 채택하고 데이터 흐름에서 하위 구성 요소로 데이터가 흐르고 명확한 데이터 흐름과 곤란하기 쉬운 구조를 제공합니다.

vue.js vs. React : 프로젝트 별 고려 사항vue.js vs. React : 프로젝트 별 고려 사항Apr 09, 2025 am 12:01 AM

vue.js는 중소형 프로젝트 및 빠른 반복에 적합한 반면 React는 크고 복잡한 응용 프로그램에 적합합니다. 1) vue.js는 사용하기 쉽고 팀이 불충분하거나 프로젝트 규모가 작는 상황에 적합합니다. 2) React는 더 풍부한 생태계를 가지고 있으며 고성능 및 복잡한 기능적 요구가있는 프로젝트에 적합합니다.

태그를 vue로 점프하는 방법태그를 vue로 점프하는 방법Apr 08, 2025 am 09:24 AM

VUE에서 태그의 점프를 구현하는 방법에는 다음이 포함됩니다. HTML 템플릿의 A 태그를 사용하여 HREF 속성을 지정합니다. VUE 라우팅의 라우터 링크 구성 요소를 사용하십시오. javaScript 에서이. $ router.push () 메소드를 사용하십시오. 매개 변수는 쿼리 매개 변수를 통해 전달 될 수 있으며 동적 점프를 위해 라우터 옵션에서 경로가 구성됩니다.

VUE의 구성 요소 점프를 구현하는 방법VUE의 구성 요소 점프를 구현하는 방법Apr 08, 2025 am 09:21 AM

VUE에서 구성 요소 점프를 구현하는 방법은 다음과 같습니다. 라우터 링크 및 & lt; router-view & gt; 하이퍼 링크 점프를 수행하고 대상 경로로 속성을 지정합니다. & lt; router-view & gt; 현재 라우팅 된 렌더링 된 구성 요소를 표시하는 구성 요소. 프로그래밍 방식 탐색을 위해 router.push () 및 router.replace () 메소드를 사용하십시오. 전자는 역사를 구하고 후자는 기록을 떠나지 않고 현재 경로를 대체합니다.

Vue의 div로 점프하는 방법Vue의 div로 점프하는 방법Apr 08, 2025 am 09:18 AM

VUE에서 DIV 요소를 점프하는 두 가지 방법이 있습니다. VUE 라우터를 사용하고 라우터 링크 구성 요소를 추가하십시오. @Click 이벤트 리스너를 추가하고 이것을 호출하십시오. $ router.push () 메소드를 점프하십시오.

vue 점프로 값을 전송하는 방법vue 점프로 값을 전송하는 방법Apr 08, 2025 am 09:15 AM

VUE에서 데이터를 전달하는 두 가지 주요 방법이 있습니다 : Props : 일원 데이터 바인딩, 부모 구성 요소에서 자식 구성 요소로 데이터를 전달합니다. 이벤트 : 이벤트와 사용자 정의 이벤트를 사용하여 구성 요소간에 데이터를 전달합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

안전한 시험 브라우저

안전한 시험 브라우저

안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.