复杂的组件之间传值的问题,可以通过vuex、发布订阅模式(vue中叫总线机制、或者观察者模式、或者Bus)来解决

<!DOCTYPE html><html><head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="./vue.js"></script> <!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> --></head><body><div id="root"> //Tom和Cat是兄弟关系 <br> <child content="Tom"></child> <child content="Cat"></child></div><script type="text/javascript"> //往Vue.prototype上挂在一个bus属性,这个属性指向vue实例。接下来只要调用new Vue()或者创建组件的时候,每个组件上都会有bus属性。因为每个组件或者说vue实例都是通过Vue这个类来创建的,而我在Vue的类上挂了一个bus属性 Vue.prototype.bus = new Vue() Vue.component("child", { props: { content: String }, template: "<div @click='handleClick'>{{content}}</div>", methods: { handleClick: function() { //alert(this.content) //传给另一个组件(每个实例上都在开头挂载了bus属性,这个bus又是个Vue实例,所以会有$emit这个方法,就可以通过这个方法向外触发事件,这个事件触发时同时携带了一个content) this.bus.$emit("change", this.content) } }, mounted: function() { var this_ = this this.bus.$on("change", function(msg) { //alert("mounted " + msg) this_.content = msg }) } }); var vm = new Vue({ el: "#root" })</script></body></html>


(像上面这样的代码会报错,因为vue中的单项数据流,父组件传值给子组件,子组件不能改变传递过来的内容,而上面却强改这个内容)
解决办法是拷贝父组件的属性咯(拷贝给selfContent):

<!DOCTYPE html><html><head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="./vue.js"></script> <!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> --></head><body><div id="root"> //Tom和Cat是兄弟关系 <br> <child content="Tom"></child> <child content="Cat"></child></div><script type="text/javascript"> //往Vue.prototype上挂在一个bus属性,这个属性指向vue实例。接下来只要调用new Vue()或者创建组件的时候,每个组件上都会有bus属性。因为每个组件或者说vue实例都是通过Vue这个类来创建的,而我在Vue的类上挂了一个bus属性 Vue.prototype.bus = new Vue() Vue.component("child", { data: function() { return { selfContent: this.content } }, props: { content: String }, template: "<div @click='handleClick'>{{selfContent}}</div>", methods: { handleClick: function() { //alert(this.content) //传给另一个组件(每个实例上都在开头挂载了bus属性,这个bus又是个Vue实例,所以会有$emit这个方法,就可以通过这个方法向外触发事件,这个事件触发时同时携带了一个content) this.bus.$emit("change", this.selfContent) } }, mounted: function() { var this_ = this this.bus.$on("change", function(msg) { //alert("mounted " + msg) this_.selfContent = msg }) } }); var vm = new Vue({ el: "#root" })</script></body></html>

以后遇到比兄弟组件关系更复杂的传值也可以这样解决