Vue组件化编程详解

 更新时间:2025年10月22日 10:02:22   作者:yume_sibai  
文章介绍了Vue中组件的基本使用、定义、注册、书写标签和嵌套等关键步骤和注意事项,详细解释了组件的配置选项、如何通过Vue.extend创建组件以及组件实例对象与Vue实例对象的区别,还提及了单文件组件的结构和编写逻辑,并强调了组件原型链的重要性

组件:用来实现局部(特定)功能效果的代码集合。可用作复用编码,简化项目编码,提高运行效率。

一、基本使用

Vue中使用组件的三大步骤

  1. 定义组件(创建组件)
  2. 注册组件
  3. 使用组件(写组件标签)

如何定义一个组件?

(1).使用Vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几乎一样,但也有点区别:

  • el不要写,为什么?--最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器,在组件配置中配置el会报错
  • data必须写成函数,为什么?--避免组件被复用时,数据存在引用关系。

(2).备注:使用template可以配置组件结构。

如何注册组件?

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

编写组件标签

<school></school>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>基本使用</title>
        <script type="text/javascript" src="../js/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <!-- 第三步:使用组件 -->
            <Hello></Hello>
            <hr>
            <school></school>
            <hr>
            <student></student>
        </div>
    </body>

    <script type="text/javascript">
        Vue.config.productionTip = false

        // 第一步:定义shcool组件
        const school = Vue.extend({
            template:`
                <div>
                    <h2>学校名称:{{name}}</h2>
                    <h2>学校地址:{{address}}</h2>
                </div>
            `,
            data() {
                return {
                    name:'清华大学',
                    address:'北京'
                }
            },
        })

        // 第一步:定义student组件
        const student = Vue.extend({
            template:`
                <div>
                    <h2>学生姓名:{{name}}</h2>
                    <h2>学生姓名:{{age}}</h2>
                </div>
            `,
            data() {
                return {
                    name:'清华',
                    age:18
                }
            },
        })

        // 第一步:定义Hello组件
        const Hello = Vue.extend({
            template:`
                <h1>欢迎学习{{msg}}!</h1>
            `,
            data() {
                return {
                    msg:'Vue'
                }
            },
        })

        //注册全局组件
        Vue.component('Hello', Hello)

        new Vue({
            el:'#root',
            //第二部:注册局部组件
            components:{
                school,
                student
            }
        })
    </script>
</html>

二、几个注意点

关于组件名

(1).一个单词组成:

  • 第一种写法(首字母小写):school
  • 第二种写法(首字母大写):School

(2).关于组件标签:

  • 第一种写法:<school></school>
  • 第二种写法:<school/>

(3).一个简写方式:

const school = Vue.extend(options) 可简写为const school = options

Vue实例对象和VueComponent实例对象的主要区别

因为组件是可复用的 Vue 实例,所以它们与new Vue接收相同的选项,

例如datacomputedwatchmethods以及生命周期钩子等。

仅有的例外是像el这样根实例特有的选项,即在VueComponent中不可以写el配置项。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>几个注意点</title>
        <script type="text/javascript" src="../js/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <h1>{{msg}}</h1>
            <hr>
            <school></school>
            <!-- 脚手架简写方式 -->
            <school/>
        </div>
    </body>

    <script type="text/javascript">
        Vue.config.productionTip = false
        
        //简写方式
        const school = {
            template:`
                <div>
                    <h2>学校名称:{{name}}</h2>
                    <h2>学校地址:{{address}}</h2>
                </div>
            `,
            data() {
                return {
                    name:'清华大学',
                    address:'北京'
                }
            },
        }

        new Vue({
            el:'#root',
            data:{
                msg:'Vue'
            },
            components:{
                school
            }
        })
    </script>
</html>

三、组件的嵌套

非单文件组件可以将多组件进行嵌套书写。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>组件的嵌套</title>
        <script type="text/javascript" src="../js/vue.js"></script>
    </head>
    <body>
        <div id="root" :x="n"></div>
    </body>

    <script type="text/javascript">
        Vue.config.productionTip = false

        //定义student组件
        const student = Vue.extend({
            template:`
                <div>
                    <h2>学生姓名:{{name}}</h2>
                    <h2>学生姓名:{{age}}</h2>
                </div>
            `,
            data() {
                return {
                    name:'清华',
                    age:18
                }
            },
        }) 

        //定义school组件
        const school = Vue.extend({
            template:`
                <div>
                    <h2>学校名称:{{name}}</h2>
                    <h2>学校地址:{{address}}</h2>
                    <student></student>
                </div>
            `,
            data() {
                return {
                    name:'清华大学',
                    address:'北京'
                }
            },
            components:{
                student
            }
        })

        //定义hello组件
        const hello = Vue.extend({
            template:`
                <div>
                    <h1>欢迎学习{{msg}}</h1>    
                </div>
            `,
            data() {
                return {
                    msg:'Vue'
                }
            },
        })

        //定义app组件
        const app = Vue.extend({
            template:`
                <div>
                    <hello></hello>
                    <school></school>
                </div>
            `,
            data() {
                return {
                    
                }
            },
            components:{
                school,
                hello
            }
        })

        new Vue({
            el:'#root',
            //这种写法会把div替换掉
            template:`
                <app></app>
            `,
            data() {
                return {
                    n:1
                }
            },
            components:{
                app
            }
        })
    </script>
</html>

四、VueComponent

关于VueComponent

1.school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的。

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

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

4.关于this的指向:

组件配置中:

  • data函数、methods中的函数、watch中的函数、computed中的函数,它们的this均是【VueComponent实例对象】

.new Vue(options)配置中:

  • data函数、methods中的函数、watch中的函数、computed中的函数,它们的this均是【Vue实例对象】

5.VueComponent的实例对象,以后简称vc(也可以称之为:组件实例对象)。Vue的实例对象,以后简称vm。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>VueComponent</title>
        <script type="text/javascript" src="../js/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <school></school>
            <hr>
            <hello></hello>
        </div>
    </body>

    <script type="text/javascript">
        Vue.config.productionTip = false

        const school = Vue.extend({
            template:`
                <div>
                    <h2>学校名称:{{name}}</h2>
                    <h2>学校地址:{{address}}</h2>
                    <button @click="output">点我显示学校名</button>
                </div>
            `,
            data() {
                return {
                    name:'清华大学',
                    address:'北京'
                }
            },
            methods: {
                output(){
                    console.log(this)
                    alert(this.name)
                }
            },
        })

        const test = Vue.extend({
            template:`
                <h2>Vue</h2>
            `,
        })

        const hello = Vue.extend({
            template:`
                <div>
                    <h2>你好{{msg}}!</h2>
                    <test></test>
                </div>
            `,
            data() {
                return {
                    msg:'Vue'
                }
            },
            components:{
                test
            }
        })


        const vm = new Vue({
            el:'#root',
            components:{
                school,
                hello
            }
        })
    </script>
</html>

五、一个重要的内置关系

VueComponent.prototype.__proto__ === Vue.prototype

为什么要有这个关系?

有了这个原型链,就可以让组件实例对象可以访问到Vue原型上的属性、方法。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>一个重要的内置关系</title>
        <script type="text/javascript" src="../js/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <school></school>
        </div>
    </body>
    <script type="text/javascript">
        Vue.config.productionTip = false

        Vue.prototype.x=99
        
        const school = Vue.extend({
            template:`
                <div>
                    <h2>学校名称:{{name}}</h2>
                    <h2>学校地址:{{address}}</h2>
                    <button @click="showX">点我输出x</button>
                </div>
            `,
            data() {
                return {
                    name:'清华大学',
                    address:'北京'
                }
            },
            methods: {
                showX(){
                    alert(this.x)
                }
            },
        })

        new Vue({
            el:'#root',
            components:{
                school
            }
        })

        console.log('@',Vue.prototype === school.prototype.__proto__) //输出为true
        // //定义一个构造函数
        // function demo(){
        //     this.a=1,
        //     this.b=2
        // }

        // demo.prototype.x=99

        // //创建一个实例对象
        // const d = new demo()

        // console.log(demo.prototype) //显示原型对象

        // console.log(d.__proto__) //隐式原型对象

        // console.log(demo.prototype === d.__proto__) //输出为true
    </script>
</html>

六、单文件组件

前面五点都使用非单文件组件进行举例,而在这一大点将简单描述单文件组件的结构与编写。注意:

1.单文件组件编写逻辑与非单文件组件逻辑大体相同,仅结构不同;

2.单文件组件请在脚手架中使用。

School.Vue创建School组件:

<template>
	<div class="demo">
		<h2>学校名称:{{name}}</h2>
		<h2>学校地址:{{address}}</h2>
		<button @click="showName">点我提示学校名</button>	
	</div>
</template>

<script>
	 export default {
		name:'School',
		data(){
			return {
				name:'尚硅谷',
				address:'北京昌平'
			}
		},
		methods: {
			showName(){
				alert(this.name)
			}
		},
	}
</script>

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

Student.Vue创建student组件:

<template>
	<div>
		<h2>学生姓名:{{name}}</h2>
		<h2>学生年龄:{{age}}</h2>
	</div>
</template>

<script>
	 export default {
		name:'Student',
		data(){
			return {
				name:'张三',
				age:18
			}
		}
	}
</script>

App.Vue将所需的组件统一引入并注册:

<template>
	<div>
		<School></School>
		<Student></Student>
	</div>
</template>

<script>
	//引入组件
	import School from './School.Vue'
	import Student from './Student.vue'

	export default {
		name:'App',
		components:{
			School,
			Student
		}
	}
</script>

main.js将编写完成的App.Vue引入页面节点中:

import App from './App.vue'

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

index.html引入main.js和Vue.js并创建在main.js中预留的节点:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>单文件组件</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>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • VUE前端导出文件之file-saver插件安装使用教程

    VUE前端导出文件之file-saver插件安装使用教程

    这篇文章主要给大家介绍了关于VUE前端导出文件之file-saver插件安装使用的相关资料,file-saver是一个用于保存文件的JavaScript库,它提供了一种简单的方式来生成和保存文件,支持各种文件类型,例如文本文件、图片、PDF等,需要的朋友可以参考下
    2024-05-05
  • elementui实现表格(el-table)默认选中功能

    elementui实现表格(el-table)默认选中功能

    这篇文章主要介绍了elementui实现表格(el-table)默认选中功能,本文给大家分享实现思路结合实例代码给大家介绍的非常详细,需要的朋友参考下吧
    2024-07-07
  • vue实现搜索并高亮文字的两种方式总结

    vue实现搜索并高亮文字的两种方式总结

    在做文字处理的项目时经常会遇到搜索文字并高亮的需求,常见的实现方式有插入标签和贴标签两种,这两种方式适用于不同的场景,各有优劣,下面我们就来看看他们的具体实现吧
    2023-11-11
  • Vue打包优化之生产环境删除console日志配置

    Vue打包优化之生产环境删除console日志配置

    这篇文章主要为大家介绍了Vue打包优化之生产环境删除console日志配置详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • Vue.js结合bootstrap前端实现分页和排序效果

    Vue.js结合bootstrap前端实现分页和排序效果

    这篇文章主要为大家详细介绍了Vue.js结合bootstrap 前端实现分页和排序效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-12-12
  • 浅谈Vue.js之初始化el以及数据的绑定说明

    浅谈Vue.js之初始化el以及数据的绑定说明

    今天小编就为大家分享一篇浅谈Vue.js之初始化el以及数据的绑定说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-11-11
  • vue导出少量pdf文件实现示例详解

    vue导出少量pdf文件实现示例详解

    这篇文章主要为大家介绍了vue导出少量pdf文件实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • vue 实现websocket发送消息并实时接收消息

    vue 实现websocket发送消息并实时接收消息

    这篇文章主要介绍了vue 实现websocket发送消息并实时接收消息,项目结合vue脚手架和websocket来搭建,本文给大家分享实例代码,需要的朋友可以参考下
    2019-12-12
  • vue关于Promise的使用方式

    vue关于Promise的使用方式

    这篇文章主要介绍了vue关于Promise的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06
  • Vue不能watch数组和对象变化解决方案

    Vue不能watch数组和对象变化解决方案

    这篇文章主要为大家介绍了Vue不能watch数组和对象变化解决方案示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-11-11

最新评论