<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>组件通信</title> </head> <body> <div id="app"> <!-- 父组件接收外面传进来的数据data_title,data_img --> <my_parent :parent_title="data_title" :parent_img="data_img"></my_parent> </div> <!-- my_img子组件模板 --> <template id="my_img"> <div> <img :src="child1_src" height="340" width="632"/> </div> </template> <!-- my_title子组件模板 --> <template id="my_title"> <h2>{{ child2_title }}</h2> </template> <!-- Parent父组件模板 --> <template id="my_parent"> <div> <child1 :child1_src="parent_img"></child1> <child2 :child2_title="parent_title"></child2> </div> </template> <script src="../js/vue.js"></script> <script src="../js/vue-router.js"></script> <script> // 创建子组件构造器 let Child1 = Vue.extend({ template: '#my_img', props: ['child1_src'], }); let Child2 = Vue.extend({ template: '#my_title', props: ['child2_title'], }); // 注册父组件 Vue.component('my_parent', { props: ['parent_title', 'parent_img'], components: { 'child1': Child1, 'child2': Child2, }, template: '#my_parent', }); // 创建Vue的实例 new Vue({ el: '#app', data:{ data_title:'小米8, 青春版, 潮流镜面渐变色', data_img:'../img/01.jpg', }, }) </script> </body> </html>
效果图:
