首頁 > web前端 > js教程 > 主體

VueJs組件之父子通訊的方式

不言
發布: 2018-05-07 14:57:36
原創
1246 人瀏覽過

這篇文章主要介紹了VueJs組件之父子通訊的方式,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下

組件(父子通訊)

一、概括

在一個元件內定義另一個元件,稱為父子元件。

   但要注意的是:1.子元件只能在父元件內部使用(寫在父親元件tempalte);

                上的資料,每個元件實例的作用域是獨立的;

那如何完成父子如何完成通訊,簡單一句話:props down, events up :父元件透過props 向下傳遞資料給子元件,子元件透過events 給父元件發送

父傳子:Props
子傳父:子:$emit(eventName) 父$on(eventName)
父存取子:ref

下面對三個進行案例講解:

二、父傳子:Props

     元件實例的作用域是孤立的。這表示不能 (也不應該) 在子元件的範本內直接引用父元件的資料。要讓子元件使用父元件的數據,需要透過子元件的props 選項

  使用Prop傳遞資料包括靜態和動態兩種形式,以下先介紹靜態props

#1、靜態props

<script src="https://unpkg.com/vue"></script>
<p id="example">
 <parent></parent>
</p>
<script>
 //要想子组件能够获取父组件的,那么在子组件必须申明:props
 var childNode = {
  template: &#39;<p>{{message}}</p>&#39;,
  props: [&#39;message&#39;]
 }
 //这里的message要和上面props中值一致
 var parentNode = {
  template: `
   <p class="parent">
   <child message="我是"></child>
   <child message="徐小小"></child>
   </p>`,
  components: {
   &#39;child&#39;: childNode
  }
 };
 // 创建根实例
 new Vue({
  el: &#39;#example&#39;,
  components: {
   &#39;parent&#39;: parentNode
  }
 })
</script>
登入後複製

效果:

 命名約定:

     對於props宣告的屬性來說,在父級HTML模板中,屬性名需要使用中劃線寫法

    子級props屬性聲明時,使用小駝峰或中劃線寫法都可以;而子級模板使用從父級傳來的變數時,需要使用對應的小駝峰寫法

上面這句話什麼意思呢?

<script>
 //这里需要注意的是props可以写成[&#39;my-message&#39;]或者[&#39;myMessage&#39;]都是可以的
 //但是template里的属性名,只能是驼峰式{{myMessage}},如果也写成{{my-message}}那么是无效的
 var childNode = {
  template: &#39;<p>{{myMessage}}</p>&#39;,
  props: [&#39;myMessage&#39;]
 }

 //这里的属性名为my-message
 var parentNode = {
  template: `
   <p class="parent">
   <child my-message="我是"></child>
   <child my-message="徐小小"></child>
   </p>`,
  components: {
   &#39;child&#39;: childNode
  }
 };
</script>
登入後複製

       如果我們childNode中的myMessage改成{{my-message}}看運行結果:

##2.動態props

    在模板中,要動態地綁定父元件的資料到子模板的props,與綁定到任何普通的HTML特性相類似,就是用v-bind。每當父元件的資料變化時,該變化也會傳導給子元件

 var childNode = {
  template: &#39;<p>{{myMessage}}</p>&#39;,
  props: [&#39;my-message&#39;]
    }

 var parentNode = {
  template: `
 <p class="parent">
 <child :my-message="data1"></child>
 <child :my-message="data2"></child>
 </p>`,
  components: {
   &#39;child&#39;: childNode
  },
  data() {
   return {
    &#39;data1&#39;: &#39;111&#39;,
    &#39;data2&#39;: &#39;222&#39;
   }
  }
 };
登入後複製

3、傳遞數字

#初學者常犯的一個錯誤是使用字面量語法傳遞數值

<script src="https://unpkg.com/vue"></script>
<p id="example">
 <parent></parent>
</p>
<script>
 var childNode = {
  template: &#39;<p>{{myMessage}}的类型是{{type}}</p>&#39;,
  props: [&#39;myMessage&#39;],
  computed: {
   type() {
    return typeof this.myMessage
   }
  }
 }
 var parentNode = {
  template: `
 <p class="parent">
 <my-child my-message="1"></my-child>
 </p>`,
  components: {
   &#39;myChild&#39;: childNode
  }
 };
 // 创建根实例
 new Vue({
  el: &#39;#example&#39;,
  components: {
   &#39;parent&#39;: parentNode
  }
 })
</script>
登入後複製

#結果:

     因為它是一個字面prop,它的值是字串"1" 而不是number。如果想傳遞一個實際的 number,需要使用 v-bind,從而讓它的值被當作JS表達式計算

#     如何把String轉成number呢,其實只要改一個地方。

 var parentNode = {
  template: `
 <p class="parent">
 //只要把父组件my-message="1"改成:my-message="1"结果就变成number类型
 <my-child :my-message="1"></my-child>
 </p>`,
 };
登入後複製

     當然你如果想要透過v-bind想傳一個string類型,那該怎麼做呢?

    我們可以使用動態props,在data屬性中設定對應的數字1

var parentNode = {
 template: `
 <p class="parent">
 <my-child :my-message="data"></my-child>
 </p>`,
 components: {
 &#39;myChild&#39;: childNode
 },
 //这里&#39;data&#39;: 1代表就是number类型,&#39;data&#39;: "1"那就代表String类型
 data(){
 return {
  &#39;data&#39;: 1
 }
 }
};
登入後複製

三、子轉父:$emit

 關於$emit的用法

   1、父元件可以用props 把資料傳給子元件。

   2、子元件可以使用 $emit 觸發父元件的自訂事件。

子主鍵

<template> 
 <p class="train-city"> 
 <span @click=&#39;select(`大连`)&#39;>大连</span> 
 </p> 
</template> 
<script> 
export default { 
 name:&#39;trainCity&#39;, 
 methods:{ 
 select(val) { 
  let data = { 
  cityname: val 
  }; 
  this.$emit(&#39;showCityName&#39;,data);//select事件触发后,自动触发showCityName事件 
 } 
 } 
} 
</script>
登入後複製

父元件

<template> 
 <trainCity @showCityName="updateCity" :index="goOrtoCity"></trainCity> //监听子组件的showCityName事件。 
<template> 
<script> 
export default { 
 name:&#39;index&#39;, 
 data () { 
 return { 
  toCity:"北京" 
 } 
 } 
 methods:{ 
 updateCity(data){//触发子组件城市选择-选择城市的事件 
  this.toCity = data.cityname;//改变了父组件的值 
  console.log(&#39;toCity:&#39;+this.toCity)  
 } 
 } 
} 
</script>
登入後複製

結果為:toCity: 大連

第二個案例

<script src="https://unpkg.com/vue"></script>

 <p id="counter-event-example">
  <p>{{ total }}</p>
  <button-counter v-on:increment1="incrementTotal"></button-counter>
  <button-counter v-on:increment2="incrementTotal"></button-counter>
 </p>
<script>
 Vue.component(&#39;button-counter&#39;, {
  template: &#39;<button v-on:click="increment">{{ counter }}</button>&#39;,
  //组件数据就是需要函数式,这样的目的就是让每个button-counter不共享一个counter
  data: function() {
   return {
    counter: 0
   } 
  },
  methods: {
   increment: function() {
   //这里+1只对button的值加1,如果要父组件加一,那么就需要$emit事件
    this.counter += 1;
    this.$emit(&#39;increment1&#39;, [12, &#39;kkk&#39;]);
   }
  }
 });
 new Vue({
  el: &#39;#counter-event-example&#39;,
  data: {
   total: 0
  },
  methods: {
   incrementTotal: function(e) {
    this.total += 1;
    console.log(e);
   }
  }
 });
</script>
登入後複製

詳細解說:

   1:button-counter作為父主鍵,父主鍵裡有個button按鈕。

   2:兩個button都綁定了click事件,方法裡:this.$emit('increment1', [12, 'kkk']);,那麼就會去呼叫父類別v-on所監聽的increment1事件。

   3:當increment1事件被監聽到,那麼執行incrementTotal,這個時候才會把值傳到父元件中,並且呼叫父類別的方法。

   4:這裡要注意第二個button-counter所對應的v-on:'increment2,而它裡面的button所對應是this.$emit('increment1', [12, 'kkk' ]);所以第二個button按鈕是無法把值傳給他的父主鍵的。

### 範例:一個按鈕點擊一次那麼它本身和上面都會自增1,而第二個按鈕只會自己自增,並不影響上面這個。 ###

还有就是第一个按钮每点击一次,后台就会打印一次如下:

四、ref ($refs)用法

ref 有三种用法

1.ref 加在普通的元素上,用this.ref.name 获取到的是dom元素

2.ref 加在子组件上,用this.ref.name 获取到的是组件实例,可以使用组件的所有方法。

3.如何利用v-for 和ref 获取一组数组或者dom 节点

1.ref 加在普通的元素上,用this.ref.name 获取到的是dom元素

<script src="https://unpkg.com/vue"></script>

<p id="ref-outside-component" v-on:click="consoleRef">
 <component-father ref="outsideComponentRef">
 </component-father>
 <p>ref在外面的组件上</p>
</p>
<script>
 var refoutsidecomponentTem = {
  template: "<p class=&#39;childComp&#39;><h5>我是子组件</h5></p>"
 };
 var refoutsidecomponent = new Vue({
  el: "#ref-outside-component",
  components: {
   "component-father": refoutsidecomponentTem
  },
  methods: {
   consoleRef: function() {
    console.log(this.); // #ref-outside-component  vue实例
    console.log(this.$refs.outsideComponentRef); // p.childComp vue实例
   }
  }
 });
</script>
登入後複製

效果:当在p访问内点击一次:

2.ref使用在外面的元素上

<script src="https://unpkg.com/vue"></script>

<!--ref在外面的元素上-->
<p id="ref-outside-dom" v-on:click="consoleRef">
 <component-father>
 </component-father>
 <p ref="outsideDomRef">ref在外面的元素上</p>
</p>
<script>
 var refoutsidedomTem = {
  template: "<p class=&#39;childComp&#39;><h5>我是子组件</h5></p>"
 };
 var refoutsidedom = new Vue({
  el: "#ref-outside-dom",
  components: {
   "component-father": refoutsidedomTem
  },
  methods: {
   consoleRef: function() {
    console.log(this); // #ref-outside-dom vue实例
    console.log(this.$refs.outsideDomRef); // <p> ref在外面的元素上</p>
   }
  }
 });
</script>
登入後複製


效果:当在p访问内点击一次:

3.ref使用在里面的元素上---局部注册组件

<script src="https://unpkg.com/vue"></script>
<!--ref在里面的元素上-->
<p id="ref-inside-dom">
 <component-father>
 </component-father>
 <p>ref在里面的元素上</p>
</p>
<script>
 var refinsidedomTem = {
  template: "<p class=&#39;childComp&#39; v-on:click=&#39;consoleRef&#39;>" +
   "<h5 ref=&#39;insideDomRef&#39;>我是子组件</h5>" +
   "</p>",
  methods: {
   consoleRef: function() {
    console.log(this); // p.childComp vue实例 
    console.log(this.$refs.insideDomRef); // <h5 >我是子组件</h5>
   }
  }
 };
 var refinsidedom = new Vue({
  el: "#ref-inside-dom",
  components: {
   "component-father": refinsidedomTem
  }
 });
</script>
登入後複製

效果:当在click范围内点击一次:

4.ref使用在里面的元素上---全局注册组件

<script src="https://unpkg.com/vue"></script>
<!--ref在里面的元素上--全局注册-->
<p id="ref-inside-dom-all">
 <ref-inside-dom-quanjv></ref-inside-dom-quanjv>
</p>
<script>
 //v-on:input指当input里值发生改变触发showinsideDomRef事件
 Vue.component("ref-inside-dom-quanjv", {
  template: "<p class=&#39;insideFather&#39;> " +
   "<input type=&#39;text&#39; ref=&#39;insideDomRefAll&#39; v-on:input=&#39;showinsideDomRef&#39;>" +
   " <p>ref在里面的元素上--全局注册 </p> " +
   "</p>",
  methods: {
   showinsideDomRef: function() {
    console.log(this); //这里的this其实还是p.insideFather
    console.log(this.$refs.insideDomRefAll); // <input type="text">
   }
  }
 });
 var refinsidedomall = new Vue({
  el: "#ref-inside-dom-all"
 });
</script>
登入後複製

效果:当我第一次输入1时,值已改变出发事件,当我第二次在输入时在触发一次事件,所以后台应该打印两次

相关推荐:

基于vue-element组件实现音乐播放器功能

VUE-地区选择器(V-Distpicker)组件的使用

以上是VueJs組件之父子通訊的方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!