vue 組件之間通信

一切從簡(jiǎn),不用webpack。

1. props $emit

主要是父子之間通信,兄弟之間通信。

<!-- html -->
<!DOCTYPE html>
<html>
<head>
<script src="http://vuejs.org/js/vue.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<div id="app">
  <p>父組件中的值parentNum: {{ parentNum }}</p>
  <add-component :transfer=parentNum @change=plus></add-component>
  <reset-component @reset=reset></reset-component>
  <button @click=fatherAdd>父組件自增</button>
</div>
</body>
</html>
Vue.component('add-component', {
  template: `
    <div>
      <div>子組件中的值childNum: {{childNum}}</div>
      <button @click="increment">子組件中自增</button>
    </div>
  `,
  props: {
    transfer: {
      Number,
    }
  },
  watch: {
    'transfer': function(childNum) {
      this.childNum = childNum;
    }
  },
  data() {
    console.warn('transfer:' + this.transfer);
    return {
       childNum: this.transfer
    }
  },
          
  methods: {
    increment() {
      this.childNum++;
      this.$emit('change', this.childNum)
    }
  },
});

Vue.component('reset-component', {
  template: `
    <div>
      <button @click=reset>重置</button>
    </div>
  `,
  methods: {
    reset() {
      this.$emit('reset');
    }
  }
});

new Vue({
  el: '#app',
  data: {
    parentNum: 0
  },
  methods: {
    fatherAdd() {
      this.parentNum += 1;
    },
    plus(newNum) {
      console.log('newNum:' + newNum);
      this.parentNum = newNum;
    },
    reset() {
      this.parentNum = 0;
    }
  }
})

父子之間通信說(shuō)明:
父組件向子組件add-component傳遞初始值parentNum,子組件通過(guò)props接受并自定內(nèi)部變量用childNum,子組件中有一個(gè)按鈕,每點(diǎn)擊一下數(shù)值就會(huì)自增1。

如果子組件用了自己的變量而不是直接用的父組件的變量,則需要通過(guò)watch來(lái)實(shí)時(shí)更新子組件的內(nèi)容 。
watch transfer表示: 一旦父組件更新了,立馬傳遞到子組件中。
子組件通過(guò)$emit方法向父組件傳遞數(shù)值。

兄弟組件通信說(shuō)明:
reset-component是add-component的兄弟組件,本示例中無(wú)法直接通信,可借助父組件通信。

2. eventBus

/新建一個(gè)Vue實(shí)例作為中央事件總嫌/
let event = new Vue();

/監(jiān)聽事件/
event.$on('eventName', (val) => {
//......do something
});

/觸發(fā)事件/
event.$emit('eventName', 'this is a message.');

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容