Vue-组件

vue组件 

在 Vue中,组件可以被视为一个独立的 Vue 实例,具有其自己的数据、模板和方法,可以独立处理其内部逻辑,与其他组件和 Vue 实例进行交互。

非单文件组件

非单文件组件是指一个文件中包含多个vue组件

非单文件组件的使用

Vue中使用组件的三大步骤:

一、定义组件(创建组件)

使用Vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几乎一样,但也有区别,区别如下:
1.el不要写 ——— 最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器。
2.data必须写成函数 ———— 避免组件被复用时,数据存在引用关系。
注:使用template可以配置组件结构。

二、注册组件

1.局部注册:靠new Vue的时候传入components选项
2.全局注册:靠Vue.component('组件名',组件)

三、使用组件(写组件标签)

<brother1></brother2>

<brother2></brother2>

代码示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="./js/vue.js"></script>
</head>
<body>
    <div id="root">
        <!-- 编辑组件标签brother1 -->
        <brother1></brother1>
        <hr>
        <!-- 编辑组件标签brother2 -->
        <brother2></brother2>
     </div>
</body>

      <script>
        Vue.config.productionTip = false
        Vue.config.devtools = true
        //创建brother1组件
        const brother1 = Vue.extend({
            template:`
              <div>
            <p>我是{{name}}</p>
            <p>我{{age}}岁</p>
             <button @click="add">点我加一{{n}}</button>
        </div>
            `,
            data(){
                return {
                    n:1,
                    name:'小明',
                    age:18
                }
            },
            methods: {
                add(){
                    this.n++
                }
            },
        })
        //创建brother2组件
        const brother2 = Vue.extend({
            template:`
              <div>
            <p>我是{{name}}</p>
            <p>我{{age}}岁</p>
        </div>
            `,
            data(){
                return {
                    name:'小亮',
                    age:19
                }
            }
        })

        //局部注册组件(此处注册组件的方式为局部注册)
        // new Vue({
        //     el:'#root',
        //     data:{

        //     },
        //     components:{
        //     brother1,
        //     brother2
        // }
        // })
        //全局注册组件
        Vue.component('brother1',brother1)
        Vue.component('brother2',brother2)
        new Vue({
            el:'#root'
        })
      </script>
</html>

运行截图:

注意事项 

1.关于组件名:

一个单词组成: 第一种写法(首字母小写):brother1

第二种写法(首字母大写):Brother1 

多个单词组成:

第一种写法(kebab-case命名):my-school

第二种写法(CamelCase命名即大驼峰命名法):MyBrother(需要Vue脚手架支持)

注:

(1).组件名尽可能回避HTML中已有的元素名称,例如:p与P都不行。  

(2).可以使用name配置项指定组件在开发者工具中呈现的名字。

  const brother1 = Vue.extend({
            name:'brother',//配置在vue开发工具中呈现的名字
            template:`
              <div>
            <p>我是{{name}}</p>
            <p>我{{age}}岁</p>
             <button @click="add">点我加一{{n}}</button>
        </div>
            `,
            data(){
                return {
                    n:1,
                    name:'小明',
                    age:18
                }
            },
            methods: {
                add(){
                    this.n++
                }
            },
        })

 在开发者工具中:

2.关于组件标签:
第一种写法:<brother></brother>
第二种写法:</brother>
注:

不用使用脚手架时,</brother>会导致后续组件不能渲染,即有多个</brother>组件标签时,只会渲染一个</brother>。

3.一个简写方式:const brother= Vue.extend(options) 可简写为:const brother= options

4.template可以配置组件结构,但需要有根节点,可以在外层使用div作为根节点,且template不能作为根节点。

 
template:`
              <div>
            <p>我是{{name}}</p>
            <p>我{{age}}岁</p>
             <button @click="add">点我加一{{n}}</button>
        </div>  
            `      //不会报错
template:`
            <p>我是{{name}}</p>
            <p>我{{age}}岁</p>
             <button @click="add">点我加一{{n}}</button>
            `        //会报错,缺乏根节点
template:`
            <p>我是{{name}}</p>
            <p>我{{age}}岁</p><button @click="add">点我加一{{n}}</button>
            `        //会报错,有两个根节点,意思是p与button写一行了
 

组件嵌套

组件嵌套:将一个组件放置在另一个组件内部。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="./js/vue.js"></script>
</head>

<body>
    <div id="root">
        <!-- 编辑组件标签 -->
        <father></father>
        <hello></hello>
        <hr>

    </div>
</body>
<script>
    Vue.config.productionTip = false
    Vue.config.devtools = true
    // 创建son组件
    const son = Vue.extend({
        template: `
             <div>
            <p>我是{{erzi}}</p>
            <p>我{{age}}岁</p>
         </div>
            `,
        data() {
            return {
                erzi: '儿子',
                age: 18
            }
        },
    })
    //创建father组件
    const father = Vue.extend({
        template: `
             <div>
            <p>我是{{baba}}</p>
            <p>我{{age}}岁</p>
            <hr>
            <son></son>
         </div>
            `,
        data() {
            return {
                baba: '爸爸',
                age: 45
            }
        },
        //局部注册son组件
        components: {
            son,
        }
    })
    // 创建hello组件
    const hello = Vue.extend({
        template: `
             <div>
            <p>{{hello}}</p>
            <p>{{info}}</p>
            <button @click="showInfo">点我提示信息</button>
         </div>
            `,
        data() {
            return {
                hello: '你好',
                info: '世界'
            }
        },
        methods: {
            showInfo() {
                alert(this.hello)
            }
        }
    })
    //创建app组件
    const app = Vue.extend({
        template: `
             <div>
            <father></father>
            <hr>
            <hello></hello>
         </div>
            `,
        //注册father与hello组件
        components: {
            father,
            hello
        }
    })
    //注册app组件
    const vm=new Vue({
        template: `
            <app></app>
            `,
        el: '#root',
        components: {
            app,
        }
    })
</script>

</html>

VueComponent     

VueComponent 是 Vue框架中的一个核心概念,指的是一个 Vue 组件的实例。当你创建一个 Vue 组件的实例时,Vue 会返回一个 VueComponent 实例。这个实例是一个包含组件状态和方法的对象。        

关于VueComponent:

1.上面代码示例中的hello组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的。

 2.我们只需要写<hello/>或<hello></hello>,Vue解析时会帮我们创建school组件的实例对象,即Vue帮我们执行的:new VueComponent(options)。

 3.特别注意:每次调用Vue.extend,返回的都是一个全新的VueComponent!!!!

 4.关于this指向:
(1).组件配置中:data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【VueComponent实例对象】。
(2).new Vue(options)配置中:data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【Vue实例对象】。

5.Vue实例对象与VueComponent组件对象是一种管理的关系。

上述代码案例中控制台输入vm,可以看到vm实例下存在$children。

一个重要的内置关系       

1.一个重要的内置关系:VueComponent.prototype.__proto__ === Vue.prototype

2.为什么要有这个关系:让组件实例对象(VueComponent)可以访问到 Vue原型上的属性、方法。  

3.原理图:

下面通过代码验证这个内置关系。    

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="./js/vue.js"></script>
</head>
<body>
    <div id="root">
         <hello></hello>
    </div>
</body>
    <script>
        Vue.config.productionTip = false
        Vue.config.devtools = true
        Vue.prototype.info='hello world!'

            // 创建hello组件
    const hello = Vue.extend({
        template: `
             <div>
            <p>{{hello}}</p>
            <p>{{world}}</p>
            <button @click="showInfo">点我提示信息</button>
         </div>
            `,
        data() {
            return {
                hello: '你好',
                world: '世界'
            }
        },
        methods: {
            showInfo() {
                console.log(this.info)   //验证是否可以访问沿原型链访问到vue原型对象中的info
            }
        }
    })

     new Vue({
            el:'#root',
            components:{
                hello,
            }
        })
    console.log(hello.prototype.__proto__ === Vue.prototype)  //验证这个内置关系是否成立
//         //定义一个构造函数
//         function Persons(name,age){
//             this.name = name,
//             this.age = age
// }       
//           const p = new Persons('小明',18)

//           console.log(Persons.prototype)  //显示原型属性

//           console.log(p.__proto__)   //隐式原型属性

//           console.log(Persons.prototype === p.__proto__)

//           Persons.prototype.age = 20
//           console.log('即将输出p')
//           console.log(p)
      
    </script>
</html>

  控制台输出可以验证VueComponent.prototype.__proto__ === Vue.prototype

 单文件组件

单文件组件:指一个文件中只包含一个vue组件。将组件的模板、脚本和样式集中在一个文件中进行管理。通常以 .vue 后缀命名。

一个典型的单文件组件会包含以下三个部分:

  1. 模板(Template):用于定义组件的 HTML 结构。
  2. 脚本(Script):包含组件的逻辑代码,如数据、方法、生命周期钩子等。
  3. 样式(Style):用于定义组件的 CSS 样式,可以是全局样式或者局部样式。

单文件组件的好处包括:

  • 模块化:将相关代码放在一起,更易于维护和理解。
  • 可重用性:组件可以被重复使用,提高开发效率。
  • 更好的工作流:通过构建工具(如 Webpack)可以方便地处理组件的编译、热重载等功能。

下面通过一个里】例子演示单文件组件的创建过程 

①先分别创建Brother.vue和Sister.vue

<template>
	<div class="demo">
		<h2>名字:{{name}}</h2>
		<h2>年龄:{{age}}</h2>
        <h2>性别:{{sex}}</h2>
		<button @click="showName">点我显示名字</button>	
	</div>
</template>

<script>
	 export default {
		name:'Brother',
		data(){
			return {
				name:'小明',
				age:18,
                sex:'男'
			}
		},
		methods: {
			showName(){
				alert(this.name)
			}
		},
	}
</script>

<style>
	.demo{
		background-color: blue;
	}
</style>

Sister.vue

<template>
	<div class="demo">
		<h2>名字:{{name}}</h2>
		<h2>年龄:{{age}}</h2>
        <h2>性别:{{sex}}</h2>
		<button @click="showName">点我显示名字</button>	
        <hr></hr>
	</div>
</template>

<script>
	 export default {
		name:'Sister',
		data(){
			return {
				name:'小红',
				age:18,
                sex:'女'
			}
		},
		methods: {
			showName(){
				alert(this.name)
			}
		},
	}
</script>

<style>
	.demo{
		background-color: orange;
	}
</style>

创建全局组件App.vue注册Brother组件和Sister组件。

<template>
	<div>
		<Brother></Brother>
		<Sister></Sister>
	</div>
</template>

<script>
	//引入组件
	import Brother from './Brother.vue'
	import Sister from './Sister.vue'

	export default {
		name:'App',
		components:{
			Brother,
			Sister
		}
	}
</script>

在项目的入口文件中main.js注册全局组件App

import App from './App.vue'

new Vue({
	el:'#root',
	template:`<App></App>`,
	components:{App},
})

在index.html使用

<!DOCTYPE html>

<html>

	<head>

		<meta charset="UTF-8" />

		<title>demo</title>

	</head>

	<body>

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

		<!-- <script type="text/javascript" src="../js/vue.js"></script> -->

		<!-- <script type="text/javascript" src="./main.js"></script> -->

	</body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值