一.Vue單層組件的通訊:html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue的全局組件</title> </head> <body> <div id="app"> <my-div message='思思最好了'></my-div> <my-div message='思思最棒了'></my-div> </div> <!-- 定義組件 --> <template id="my-div"> <div><p>{{message}}</p></div> </template> <script src="js/vue.js"></script> <script> // 建立組件 注意這裏要加#號,否則不能顯示 Vue.component('my-div', { template: '#my-div', props: ['message'] }); // 建立vue的實例 let vm = new Vue({ el: '#app', data: { name: 'si peng' }, }); </script> </body> </html>
二.多層組件的通訊:必須經過動態綁定vue
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue多層組件間的通訊</title> </head> <body> <div id="app"> <my-parent :imgsrc="img" :title="title"></my-parent> </div> <!-- 子組件1 --> <template id="my-image"> <img src="imgsrc" width="200"> </template> <!-- 子組件2 --> <template id="my-title"> <he>{{title}}</he> </template> <!-- 父組件 --> <template id="my-parent"> <div> <my-child1 :imgsrc='imgsrc'></my-child1> <my-child2 :title='title'></my-child2> </div> </template> <script src="js/vue.js"></script> <script> // 子組件的實例 let child1 = Vue.extend({ template: '#my-image', props: ['imgsrc'] }) let child2 = Vue.extend({ template: '#my-title', props: ['title'] }) // 註冊父組件 Vue.component('my-parent', { props: ['imgsrc', 'title'], components: { 'child1': child1, 'child2': child2 }, template: '#my-parent' }) // 建立vue的實例 let vm = new Vue({ el: '#app', data: { title: '思思,週末快樂啊!', img: 'images/3.jpeg' }, }); </script> </body> </html>