>  기사  >  웹 프론트엔드  >  vue.js를 사용하여 $refs 및 $emit 상위-하위 구성 요소 상호 작용을 구현하는 방법

vue.js를 사용하여 $refs 및 $emit 상위-하위 구성 요소 상호 작용을 구현하는 방법

亚连
亚连원래의
2018-06-19 16:11:101428검색

이 글에서는 주로 vue.js $refs와 $emit parent-child 컴포넌트 간의 상호작용 방식을 소개하고 있습니다.

이 글에서는 vue.js $refs와 $emit parent-child 구성 요소 간의 상호 작용 방법을 소개합니다. 더 이상 고민할 필요 없이 코드만 살펴보겠습니다.

<strong>父调子 $refs (把父组件的数据传给子组件) </strong><br><br><template>
 <p id="app">
  <input type="button" name="" id="" @click="parentCall" value="父调子" />
  <hello ref="chil" />//hello组件
 </p>
</template>
<script>
 import hello from &#39;./components/Hello&#39;
 export default {
  name: &#39;app&#39;,
  &#39;components&#39;: {
   hello
  },
  methods: {
    parentCall () {
      this.$refs.chil.chilFn(&#39;我是父元素传过来的&#39;)
    }
  }
 }
</script>
/*Hello.vue :*/
<template>
 <p class="hello"></p>
</template>
<script>
 export default {
  name: &#39;hello&#39;,
  &#39;methods&#39;: {
    chilFn (msg) {
      alert(msg)
    }
  }
 }
</script>
<strong>子调父 $emit (把子组件的数据传给父组件)</strong>
//ps:App.vue 父组件
//Hello.vue 子组件
<!--App.vue :-->
<template>
  <p id="app">
    <hello @newNodeEvent="parentLisen" />
  </p>
</template>
<script>
 import hello from &#39;./components/Hello&#39;
 export default {
  name: &#39;app&#39;,
  &#39;components&#39;: {
   hello
  },
  methods: {
   parentLisen(evtValue) { 
    //evtValue 是子组件传过来的值
    alert(evtValue)
   }
  }
 }
</script>
<!--Hello.vue :-->
<template>
  <p class="hello">
    <input type="button" name="" id="" @click="chilCall()" value="子调父" /> 
  </p>
</template>
<script>
 export default {
  name: &#39;hello&#39;,
  &#39;methods&#39;: {
   chilCall(pars) {
    this.$emit(&#39;newNodeEvent&#39;, &#39;我是子元素传过来的&#39;)
   }
  }
 }
</script>

위 내용은 제가 작성한 내용입니다. 앞으로 도움이 되길 바랍니다.

관련 기사:

JavaScript에서 개체 값을 병합하는 방법에 대해

Angular에서 확인을 구현하는 방법

Angular에서 테이블 정렬을 구현하는 방법

localstorage 및 Vue 정보 사용 방법 세션저장

위 내용은 vue.js를 사용하여 $refs 및 $emit 상위-하위 구성 요소 상호 작용을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.