流程:创建组件构造器->注册组件->使用
<div id="app"> <my-date></my-date> </div> <script src="js/vue.js"></script> <script> // 1.创建组件构造器 let Profile = Vue.extend({ // 模板选项 template: ` <div> <input type="date"> <p>今天已经是冬天了!</p> </div> ` }); // 2.注册全局组件 Vue.component('my-date', Profile); new Vue({ el: '#app', }); </script>在vue实例化对象里面通过components键值对注册
<div id="app"> <my-date></my-date> <my-color></my-color> </div> <script src="js/vue.js"></script> <script> // 1.创建组件构造器 let Profile = Vue.extend({ // 模板选项 template: ` <div> <input type="date"> <p>今天已经是冬天了!</p> </div> ` }); let Profile2 = Vue.extend({ template: ` <div> <input type="color"> <p>我是一个色板!</p> </div> ` }); new Vue({ el: '#app', components: { 'my-date': Profile, 'my-color': Profile2 } }); </script>父组件传递数据给子组件
<div id="app"> <my-div message="今天要下雨" imgsrc="img/img_01.jpg"></my-div> <my-div message="明天要下雪" imgsrc="img/img_02.jpg"></my-div> </div> <template id="my_div"> <div> <h1>{{message}}</h1> <img :src="imgsrc" width="100"> <!--不支持驼峰式写法imgSrc--> </div> </template> <script src="js/vue.js"></script> <script> Vue.component('my-div', { template: '#my_div', props: ['message', 'imgsrc'] }) new Vue({ el: '#app', }); </script>注意:多层组件之间的属性传递必须通过动态绑定
<div id="app"> <my-parent :imgtitle="title" :imgsrc="img"></my-parent> </div> <template id="my_img"> <img :src="imgsrc" width="200"> </template> <template id="my_title"> <h1>{{title}}</h1> </template> <template id="my_parent"> <div> <child1 :imgsrc="imgsrc"></child1> <child2 :title = "imgtitle"></child2> </div> </template> <script src="js/vue.js"></script> <script> // 1.子组件的实例 let Child1 = Vue.extend({ template: '#my_img', props: ['imgsrc'] }); let Child2 = Vue.extend({ template: '#my_title', props: ['title'] }); // 2.注册父组件 Vue.component('my-parent', { props: ['imgtitle', 'imgsrc'], components: { 'child1': Child1, 'child2': Child2 }, template: '#my_parent' }) new Vue({ el: '#app', data: { title: '我是不是很漂亮', img: 'img/img_01.jpg' } }); </script>