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

如何使用VueJs元件父子通訊(附程式碼)

php中世界最好的语言
發布: 2018-05-31 10:39:45
原創
1214 人瀏覽過

這次帶給大家如何使用VueJs元件父子通訊(附程式碼),使用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: '<p>{{message}}</p>',
  props: ['message']
 }
 //这里的message要和上面props中值一致
 var parentNode = {
  template: `
   <p class="parent">
   <child message="我是"></child>
   <child message="徐小小"></child>
   </p>`,
  components: {
   'child': childNode
  }
 };
 // 创建根实例
 new Vue({
  el: '#example',
  components: {
   'parent': parentNode
  }
 })
</script>
登入後複製

效果:

 命名約定:

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

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

上面這句話什麼意思呢?

<script>
 //这里需要注意的是props可以写成['my-message']或者['myMessage']都是可以的
 //但是template里的属性名,只能是驼峰式{{myMessage}},如果也写成{{my-message}}那么是无效的
 var childNode = {
  template: '<p>{{myMessage}}</p>',
  props: ['myMessage']
 }
 //这里的属性名为my-message
 var parentNode = {
  template: `
   <p class="parent">
   <child my-message="我是"></child>
   <child my-message="徐小小"></child>
   </p>`,
  components: {
   'child': childNode
  }
 };
</script>
登入後複製

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

2.動態props

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

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

3、傳遞數字

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

<script src="https://unpkg.com/vue"></script>
<p id="example">
 <parent></parent>
</p>
<script>
 var childNode = {
  template: '<p>{{myMessage}}的类型是{{type}}</p>',
  props: ['myMessage'],
  computed: {
   type() {
    return typeof this.myMessage
   }
  }
 }
 var parentNode = {
  template: `
 <p class="parent">
 <my-child my-message="1"></my-child>
 </p>`,
  components: {
   'myChild': childNode
  }
 };
 // 创建根实例
 new Vue({
  el: '#example',
  components: {
   'parent': 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: {
 'myChild': childNode
 },
 //这里'data': 1代表就是number类型,'data': "1"那就代表String类型
 data(){
 return {
  'data': 1
 }
 }
};
登入後複製

三、子轉父:$emit

# 關於$emit的用法

   1、父元件可以使用props 把資料傳給子元件。
   2、子元件可以使用 $emit 觸發父元件的自訂事件。

子主鍵

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

父元件

<template> 
 <trainCity @showCityName="updateCity" :index="goOrtoCity"></trainCity> //监听子组件的showCityName事件。 
<template> 
<script> 
export default { 
 name:'index', 
 data () { 
 return { 
  toCity:"北京" 
 } 
 } 
 methods:{ 
 updateCity(data){//触发子组件城市选择-选择城市的事件 
  this.toCity = data.cityname;//改变了父组件的值 
  console.log('toCity:'+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('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  //组件数据就是需要函数式,这样的目的就是让每个button-counter不共享一个counter
  data: function() {
   return {
    counter: 0
   } 
  },
  methods: {
   increment: function() {
   //这里+1只对button的值加1,如果要父组件加一,那么就需要$emit事件
    this.counter += 1;
    this.$emit('increment1', [12, 'kkk']);
   }
  }
 });
 new Vue({
  el: '#counter-event-example',
  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时,值已改变出发事件,当我第二次在输入时在触发一次事件,所以后台应该打印两次

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样使用Vue实现树形视图数据

JS对DOM树实现遍历有哪些方法

以上是如何使用VueJs元件父子通訊(附程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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