第十七课 component组件解析

component组件解析

component组件的写法在众多组件写法中算是比较简单的,component组件结构组成如下:

1)组件名

2)组件模板

3)利用Vue对象进行生成

基础示例:

复制代码
    <div id="app">
        <test></test>
    </div>

    <script>
        Vue.component('test', {
            template: '<h1>这是一个组件模板</h1>'
        })

        new Vue({
            el:'#app'
        })
    </script> 

component组件

我们可以通过在实例外部以component的方式拓展单个组件,当前方式需要在构建全局实例之前进行组件创建,不存在组件提升。(类似于变量提升)

1)创建组件

复制代码
    <div id="app">
        <test></test>
    </div>

    <script>
        Vue.component('test', {
            template: '<h1>这是一个组件模板</h1>'
        })

        new Vue({
            el:'#app'
        })
    </script> 

2)分离模板创建组件

复制代码
    <div id="app">
        <test></test>
    </div>

    <script>
        let tem = {
            template: '<h1>这是一个组件模板</h1>'
        }

        Vue.component('test', tem);

        new Vue({
            el:'#app'
        })
    </script> 

3)通过components拓展组件

components和methods类似,表示(组件)集合,我们也可以直接通过components进行组件拓展

复制代码
    <div id="app">
        <test></test>
    </div>

    <script>
        new Vue({
            el:'#app',
            components: {
                'test': {
                    template: '<h1>这是一个组件模板</h1>'
                }
            }
        })
    </script> 

驼峰式命名

驼峰式命名在使用的时候,需要将调用的组件名转换成横杠式

复制代码
    <div id="app">
        <test-me></test-me>
    </div>

    <script>
        Vue.component('testMe', {
            template: '<h1>这是一个组件模板</h1>'
        })

        new Vue({
            el:'#app'
        })
    </script>  

组件中的DOM包裹规则

1)单DOM组件

复制代码
    <div id="app">
        <test></test>
    </div>

    <script>
        Vue.component('test', {
            template: '<h1>这是一个组件模板</h1>'
        })

        new Vue({
            el:'#app'
        })
    </script> 

2)多DOM组件

如果组件涉及的DOM较多,必须要将所有DOM包裹在一个主DOM中,否则将报错

复制代码
    <div id="app">
        <test></test>
    </div>

    <script>
        Vue.component('test', {
            template: '<div><h1>这是一个组件模板</h1><h1>这是第二个组件模板</h1></div>'
        })

        new Vue({
            el:'#app'
        })
    </script> 

3)配合ES6模板语法使用

复制代码
    <div id="app">
        <test></test>
    </div>

    <script>
        Vue.component('test', {
            template: `<div>
                            <h1>这是一个组件模板</h1>
                            <h1>这是第二个组件模板</h1>
                      </div>`
        })

        new Vue({
            el:'#app'
        })
    </script> 
相关推荐
陈随易4 分钟前
VSCode v1.102发布,AI体验大幅提升
前端·后端·程序员
markyankee1015 分钟前
Vue 表单输入绑定终极指南:从基础到企业级实践
vue.js
ma778 分钟前
JavaScript 获取短链接原始地址的解决方案
前端
该用户已不存在8 分钟前
关于我把Mac Mini托管到机房,后续来了,还有更多玩法
服务器·前端·mac
借月10 分钟前
🎯 用 Vue + SVG 实现一个「蛇形时间轴」组件,打造高颜值事件流程图
vue.js
tianchang11 分钟前
SSR 深度解析:从原理到实践的完整指南
前端·vue.js·设计模式
闲蛋小超人笑嘻嘻12 分钟前
前端面试十一之TS
前端
摆烂为不摆烂12 分钟前
😁深入JS(四): 一文让你完全了解Iterator+Generator 实现async await
前端
DoraBigHead25 分钟前
🧠 别急着传!大文件上传里,藏着 Promise 的高级用法
前端·javascript·面试
嘉琪00128 分钟前
封装一个有最小化的dialog组件
前端·javascript·css