Vue-组件
  gG0h9qba9eQk 2024年03月23日 11 0
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

三、单文件组件

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年03月23日 0

暂无评论

推荐阅读
  qi45EmQmijLD   14天前   27   0   0 Vue
gG0h9qba9eQk
作者其他文章 更多

2024-03-25

2024-03-23

2024-03-22