本教程只講 Vue 自己的組件通訊,不涉及借用第三方如 Vuex 之類的插件。組件通訊主要分爲三個部分:javascript
<div id="app"> <p><label>父組件</label><input type="text" v-model="txt"/></p> <child1 :txt="txt"></child1> </div> <script type="text/javascript"> var vm = new Vue({ el: '#app1', data: { txt: "" }, components: { 'child1': { props: ['txt'], template: '<h1>{{this.txt}}</h1>' } } }) </script>
效果預覽html
<div id="app"> <p><label>父組件</label><input type="text" v-model="txt"/></p> <child1 ref="c1"></child1> </div> <script type="text/javascript"> var vm = new Vue({ el: '#app', methods: { change: function(event){ this.$refs.c1.childEvent(event.target.value); } }, components: { 'child': { template: '<h1>{{this.txt}}</h1>', data: function(){ return {txt: ''}; }, methods: { childEvent: function(_txt){ this.txt = _txt; } } } } }) </script>
效果預覽vue
<div id="app"> <p><label>父組件</label><input type="text" v-model="txt"/></p> <child1></child1> </div> <script type="text/javascript"> var vm = new Vue({ el: '#app', methods: { change: function(event){ this.$children[0].childEvent(event.target.value); } }, components: { 'child': { template: '<h1>{{this.txt}}</h1>', data: function(){ return {txt: ''}; }, methods: { childEvent: function(_txt){ this.txt = _txt; } } } } }) </script>
效果預覽java
父組件在組件的生命週期用 on
定義事件,子組件用 this.$parent.$emit
調用父組件的事件。git
<div id="app"> <h1>父組件-{{this.txt}}</h1> <child></child> </div> <script type="text/javascript"> var vm = new Vue({ el: '#app', data: { txt: '' }, mounted: function(){ this.$on('parentEvent', function(_txt){ this.txt = _txt; }) }, components: { 'child': { template: '<p><label>子組件</label><input type="text" v-on:input="change"/></p>', methods: { change: function(event){ this.$parent.$emit('parentEvent', event.target.value) } } } } }) </script>
效果預覽github
父組件在調用子組件時用 v-on
把事件傳給子組件,子組件用 this.$emit
調用父組件傳過來的事件。app
<div id="app"> <h1>父組件-{{this.txt}}</h1> <child v-on:parentevent="changeTxt"></child> </div> <script type="text/javascript"> var vm = new Vue({ el: '#app', data: { txt: '' }, methods: { changeTxt: function(_txt){ this.txt = _txt; } } , components: { 'child': { template: '<p><label>子組件</label><input type="text" v-on:input="change"/></p>', methods: { change: function(event){ this.$emit('parentevent', event.target.value) } } } } }) </script>
效果預覽this
父組件在調用子組件時用 v-on
把事件傳給子組件,子組件用 this.$emit
調用父組件傳過來的事件。插件
<div id="app"> <h1>父組件-{{this.txt}}</h1> <child></child> </div> <script type="text/javascript"> var vm = new Vue({ el: '#app', data: { txt: '' }, methods: { changeTxt: function(_txt){ this.txt = _txt; } } , components: { 'child': { template: '<p><label>子組件</label><input type="text" v-on:input="change"/></p>', methods: { change: function(event){ this.$parent.changeTxt(event.target.value); } } } } }) </script>
效果預覽code
和上面介紹的父子之間通訊是同樣的,由於任何兩個子組件之間,都會擁有一個共同的父級組件,因此兄弟組件之間的通訊就是子1向父,而後再父向子2,這樣來達到兄弟之間組件的通訊。