子組件向父組件傳值時,在子組件內部添加事件,當事件觸發時進行數據操做,在事件處理函數中經過$emit觸發父組件的自定義事件,實質上是子組件的事件觸發後會觸發父組件的自定義件,父組件能夠在使用子組件的地方直接用 v-on 來監聽子組件觸發的事件。父組件向子組件傳值利用props自定義一個屬性,將須要傳遞的數據賦值給該屬性,子組件就能夠接收到數據。
總結:父子組件之間的傳值都是經過對一個媒介,父傳子是經過子組件定義的屬性,子傳父是經過父組件的自定義事件javascript
<div id="app"> <p>{{ sum }}</p> <button-counter :title='msg' @add='changeSum'></button-counter> <button-counter @add='changeSum'></button-counter> </div>
Vue.component ('button-counter', { template: `<button @click='clickHandel'>{{ this.count }}</button>`, data () { return { count: 0 } props: ['title'] }, methods: { clickHandel () { this.count ++, this.$emit('add') console.log(this.title) } } }) new Vue ({ el: '#app', data () { return { sum: 0 } }, methods: { changeSum () { this.sum ++ } } })
// bus.js import Vue from 'vue' var bus = new Vue() export default bus // module.exports = bus
兩個非父子組件html
// A <template> <div> <button @click="sendToB">toB</button> </div> </template> <script> import Bus from './bus' export default { methods:{ sendToB: function () { Bus.$emit('toBFlag','hello') } } } </script> <style> </style>
// B <template> </template> <script> import Bus from './bus' export default { created: function () { Bus.$on('toBFlag',function (data) { console.log(data) }) } } </script> <style> </style>