首頁  >  文章  >  web前端  >  利用vue.js如何實作$refs和$emit 父子元件交互

利用vue.js如何實作$refs和$emit 父子元件交互

亚连
亚连原創
2018-06-19 16:11:101411瀏覽

本篇文章主要介紹了vue.js $refs和$emit 父子元件互動的方法,現在分享給大家,也給大家做個參考。

本文介紹了vue.js $refs和$emit 父子元件互動的方法,分享給大家,廢話不多說直接看程式碼:

<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使用中Object值如何合併

在Angular中如何實作驗證

在Angular中如何實作table表格排序

在Vue中有關於localstorage和sessionstorage如何使用

以上是利用vue.js如何實作$refs和$emit 父子元件交互的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn