Vue.js -- 全局组件&局部组件

85 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第8天,点击查看活动详情

vue组件

组件是 Vue.js 最强大的功能之一,组件可以扩展 HTML 元素,封装可重用的代码。组件系统让我们可以用独立可复用的小组件来构建大型应用,几乎任意类型的应用的界面都可以抽象为一个组件树。

在这里插入图片描述

全局组件

全局组件,全局可用,使用简单,性能不高

组件定义

代码演示:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>vue组件</title>
    <!-- 使用CDN引入Vue -->
    <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
    <div id="root"></div>
    <script>
        const app = Vue.createApp({
            template:`
            <div>
                <hello />
            </div>
            `
        })
        app.component('hello', {
            template:`<div>hello</div>`
        })
        const vm = app.mount('#root');
    </script>
</body>
</html>

页面效果:

在这里插入图片描述

组件复用

组件可以复用,但数据是独立的

代码演示:

	const app = Vue.createApp({
            template:`
            <div>
                <hello />
                <hello />
                <hello />
                <hello />
            </div>
            `
        })
        app.component('hello', {
            data(){
                return {
                    content: "0"
                }
            },
            template:`<div @click="content++">hello {{content}}</div>`
        })

页面效果: 在这里插入图片描述

组件的组件

代码演示:

     const app = Vue.createApp({
           
            template:`
            <div>
                <parent />
                <hello />
                <hello />
                <hello />
            </div>
            `
        })
        app.component('parent', {
            template:`<div ><Hello /></div>`
        })
        app.component('hello', {
            data(){
                return {
                    content: "0"
                }
            },
            template:`<div @click="content++">hello {{content}}</div>`
        })

页面效果: 在这里插入图片描述

局部组件

局部组件定义后需要注册才能使用,性能较高,使用起来比较麻烦。

代码演示:

 	// 局部组件
        const Demo = {
            template:`<div >局部组件</div>`
        }
        const app = Vue.createApp({
            components:{ Demo },	//将使用的局部组件注册进来
            template:`
            <div>
                <Demo />
            </div>
            `
        })

页面效果: 在这里插入图片描述

总结

全局组件,全局可用,使用简单,性能不高;

组件可以复用,但数据是独立的;

局部组件定义后需要注册才能使用,性能较高,使用起来比较麻烦;

结语

本小节到此结束,谢谢大家的观看!

如有问题欢迎各位指正