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

vue组件

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

在这里插入图片描述

全局组件

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

组件定义

代码演示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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>`
        })

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

组件的组件

代码演示:

onst 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>
            `
        })

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

总结

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

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

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

(完)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱划水de鲸鱼哥~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值