1.什么是组件
-
组件是可复用的Vue实例,也就是一组可以复用的模版,类似JSTL的自定义标签。
-
你可能会有页头、侧边栏、内容区等组件,每个组件又包含了其它的像导航链接、博文之类的组件。
2.第一个Vue组件
注意:在实际开发中,我们并不会用以下方式开发组件,而是采用 vue-cli 创建 .vue 模板文件的方式开发,以下方法只是为了让大家理解什么是组件。
1.使用 Vue.component() 方法注册组件,格式如下:
- Vue.componet():注册组件
- props属性:用来传递参数,注意:默认规则下props属性里的值不能为大写
- first_component:自定义组件的名字
- template:自定义组件需要执行的模版
说明:
- v-for="item in items" :遍历
Vue
实例中定义的名为items
的数组,并创建同等数量的组件 - v-bind:item="item" :将遍历的
item
项绑定到组件中props
定义的名为item
属性上;= 号左边的 item 为 props 定义的属性名,右边的为item in items
中遍历的 item 项的值
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <!--view层模块--> 9 <div id="vue"> 10 11 <!--组件:传递给组件中的值:props--> 12 <first_component v-for="item in items" v-bind:com="item"></first_component> 13 </div> 14 15 <!--导入Vue.js--> 16 <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script> 17 <script type="text/javascript"> 18 19 //定义一个Vue组件 20 Vue.component("first_component", { 21 props: ["com"], 22 template: "<li>{{com}}</li>" 23 }) 24 25 let vm = new Vue({ 26 el: '#vue', 27 data: { 28 items: ["java", "C++", "C#", "Python", "PHP"] 29 }, 30 31 }); 32 </script> 33 </body> 34 </html>