父子间的组件通信 今天来总结一下Vue中的组件通信,参考了官方教程和某些博客 父子间的通信有两种,一种是从父到子,另一种是从子到父
从父到子 一般使用props1 2 3 4 5 6 Vue.component('blog-post' , { props: ['postTitle' ], template: '<h3>{{ postTitle }}</h3>' }) <blog-post post-title="hello!" ></blog-post >
从子到父 使用emit1 2 <single-address @edit-address="editAddress" ></single-address >
1 2 3 4 5 6 methods: { editAddress () { this .$emit('edit-address' , false ) } }
兄弟间的组件通信 使用event bus1 2 3 4 5 6 7 var bus = new Vue()bus.$emit('id-selected' , 1 ) bus.$on('id-selected' , function (id ) { console .log(id) })
祖孙间的组件通信 依赖注入,使用 provide 和 inject1 2 3 4 5 6 <google-map > <google-map-region v-bind:shape ="cityBoundaries" > <google-map-markers v-bind:places ="iceCreamShops" > </google-map-markers > </google-map-region > </google-map >
1 2 3 4 5 6 7 provide: function ( ) { return { getMap: this .getMap } }
另外一些方法
1 2 3 4 5 6 7 8 9 10 11 12 this .$refsvar req = new XMLhttpRequest()req.open('GET' ,'' ,true ) req.onreadystatechange=function ( ) { if (req.readyState==4 &&req.status==200 ){ var str = req.responseText console .log(str) } } req.send()