Vue-组件

  • Vue-组件已关闭评论
  • 41 次浏览
  • A+
所属分类:Web前端
摘要

Vue基于可以重用、独立的思想,设计出组件这一概念,组件可以使程序员对每个部分进行单独设计。


Vue 组件

一、概念

Vue基于可以重用、独立的思想,设计出组件这一概念,组件可以使程序员对每个部分进行单独设计。

如下图为组件很形象的定义

![image-20240322222233651](/Users/zhangqi/Library/Application Support/typora-user-images/image-20240322222233651.png)

二、非单文件组件

1.组件的基础使用

<div id="root">   <student></student> </div> 

局部组件以及注册

//第一步:创建student组件 const student = Vue.extend({//此处school即为Vue创建的组件   name:'Student',//首字母大写,约定俗成。Vue在用该组件时,会自动将首字母大写   template:``,//可以在此处写简单的模板   data(){//组件内的data,是以对象形式保存的,不可以写成数组形式     return {       name:"张三",       age:19     }   },   methods: {        } }) new Vue({   el:'#root',   data:{     msg:'你好啊!'   },   //第二步:注册组件(局部注册)   components:{     student   } }) 

全局组件以及注册

<div id="root">   <hello></hello> </div> 
//第一步:创建hello组件 const hello = Vue.extend({   template:` 				<div>	 					<h2>你好啊!{{name}}</h2> 				</div> 			`,   data(){     return {       name:'Tom'     }   } })  //第二步:全局注册组件 Vue.component('hello',hello)  new Vue({   el:'#root2', }) 

2.组件的嵌套

<script type="text/javascript">  Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。  //定义student组件 const student = Vue.extend({   name:'student',   template:` 				<div> 					<h2>学生姓名:{{name}}</h2>	 					<h2>学生年龄:{{age}}</h2>	 				</div> 			`,   data(){     return {       name:'尚硅谷',       age:18     }   } })  //定义school组件 const school = Vue.extend({   name:'school',   template:` 				<div> 					<h2>学校名称:{{name}}</h2>	 					<h2>学校地址:{{address}}</h2>	 					<student></student> 				</div> 			`,   data(){     return {       name:'尚硅谷',       address:'北京'     }   },   //注册组件(局部)   components:{     student   } })  //定义hello组件 const hello = Vue.extend({   template:`<h1>{{msg}}</h1>`,   data(){     return {       msg:'欢迎来到尚硅谷学习!'     }   } })  //定义app组件 const app = Vue.extend({   template:` 				<div>	 					<hello></hello> 					<school></school> 				</div> 			`,   components:{     school,     hello   } })  //创建vm new Vue({   template:'<app></app>',   el:'#root',   //注册组件(局部)   components:{app} }) </script> 

3.重要的内置关系

VueComponent.prototype.proto === Vue.prototype
Vue-组件

三、单文件组件

Vue-组件