本教程只讲 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,这样来达到兄弟之间组件的通讯。