Vue 自定义组件

简介: 简介组件系统是Vue.js其中一个重要的概念,它提供了一种抽象,让我们可以使用独立可复用的小组件来构建大型应用,任意类型的应用界面都可以抽象为一个组件树功能组件 (Component) 是 Vue.js 最强大的功能之一。

简介

组件系统是Vue.js其中一个重要的概念,它提供了一种抽象,让我们可以使用独立可复用的小组件来构建大型应用,任意类型的应用界面都可以抽象为一个组件树


功能

组件 (Component) 是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码。在较高层面上,组件是自定义元素,Vue.js 的编译器为它添加特殊功能。在有些情况下,组件也可以表现为用 is 特性进行了扩展的原生 HTML 元素。所有的 Vue 组件同时也都是 Vue 的实例,所以可接受相同的选项对象 (除了一些根级特有的选项) 并提供相同的生命周期钩子

组件注册

组件名

组件名应该始终是多个单词的,根组件 App 除外

这样做可以避免跟现有的以及未来的 HTML 元素相冲突,因为所有的 HTML 元素名称都是单个单词的

单文件组件的文件名应该要么始终是单词大写开头 (PascalCase),要么始终是横线连接 (kebab-case)

混用文件命名方式有的时候会导致大小写不敏感的文件系统的问题,这也是横线连接命名同样完全可取的原因

  • 使用 kebab-case
    当使用 kebab-case (短横线分隔命名) 定义一个组件时,你也必须在引用这个自定义元素时使用 kebab-case,例如 <my-component-name>
Vue.component('my-component-name', { /* ... */ })
  • 使用 PascalCase
    当使用 PascalCase (驼峰式命名) 定义一个组件时,你在引用这个自定义元素时两种命名法都可以使用。也就是说 <my-component-name><MyComponentName> 都是可接受的。注意,尽管如此,直接在 DOM (即非字符串的模板) 中使用时只有 kebab-case 是有效的
Vue.component('MyComponentName', { /* ... */ })

全局注册

以上方法都属于全局注册, 也就是说它们在注册之后可以用在任何新创建的 Vue 根实例 (new Vue) 的模板中, 比如

  • HTML
<div id="app">
  <component-a></component-a>
  <component-b></component-b>
  <component-c></component-c>
</div>
  • JS
Vue.component('component-a', { /* ... */ })
Vue.component('component-b', { /* ... */ })
Vue.component('component-c', { /* ... */ })

new Vue({ el: '#app' })

在所有子组件中也是如此,也就是说这三个组件在各自内部也都可以相互使用

局部注册

如果不需要全局注册,或者是让组件使用在其它组件内,可以用选项对象的 components 属性实现局部注册, 这里不做详述

父子组件通信

注: 本节引用 岁月如同马匹 - 简书

在vue组件通信中其中最常见通信方式就是父子组件之中的通性,而父子组件的设定方式在不同情况下又各有不同。最常见的就是父组件为控制组件子组件为视图组件。父组件传递数据给子组件使用,遇到业务逻辑操作时子组件触发父组件的自定义事件。无论哪种组织方式父子组件的通信方式都是大同小异

父组件到子组件通讯

父组件到子组件的通讯主要为:子组件接受使用父组件的数据,这里的数据包括属性和方法(String, Number, Boolean, Object, Array, Function)。vue提倡单项数据流,因此在通常情况下都是父组件传递数据给子组件使用,子组件触发父组件的事件,并传递给父组件所需要的参数

通过 props 传递数据 (推荐)

父子通讯中最常见的数据传递方式就是通过props传递数据,就好像方法的传参一样,父组件调用子组件并传入数据,子组件接受到父组件传递的数据进行验证使用

props 可以是数组或对象,用于接收来自父组件的数据。props 可以是简单的数组,或者使用对象作为替代,对象允许配置高级选项,如类型检测、自定义校验和设置默认值

prop 的定义应该尽量详细,至少需要指定其类型

<!-- 父组件 -->
<template>
    <div>
        <my-child :parentMessage="parentMessage"></my-child>
    </div>
</template>

<script>
    import MyChild from '@components/common/MyChild'

    export default {
        components: {
            MyChild
        },
        data() {
            return {
                parentMessage: "我是来自父组件的消息"
            }
        }
    }
</script>
<!-- 子组件 -->
<template>
    <div>
        <span>{{ parentMessage }}</span>
    </div>
</template>

<script>
    export default {
        props: {
            parentMessage: {
                type: String,
                default: '默认显示的信息'
            }
        }
    }
</script>

通过 $on 传递父组件方法

通过$on传递父组件方法是组件通信中常用的方法传递方式。它可以与通过props传递方法达到相同的效果。相比于props传递function,它更加的直观和显示的表现出了调用关系

<!-- 父组件 -->
<template>
    <div>
        <my-child @childEvent="parentMethod"></my-child>
    </div>
</template>

<script>
    import MyChild from '@components/common/MyChild'

    export default {
        components: {
            MyChild,
        },
        data() {
            return {
                parentMessage: '我是来自父组件的消息',
            }
        },
        methods: {
            parentMethod() {
                alert(this.parentMessage)
            }
        }
    }
</script>
<!-- 子组件 -->
<template>
    <div>
        <h3>子组件</h3>
    </div>
</template>

<script>
    export default{
        mounted() {
            this.$emit('childEvent')
        }
    }
</script>

获取父组件然后使用父组件中的数据(不推荐)

准确来说这种方式并不属于数据的传递而是一种主动的查找。父组件并没有主动的传递数据给子组件,而是子组件通过与父组件的关联关系,获取了父组件的数据。
该方法虽然能实现获取父组件中的数据但是不推荐这种方式,因为vue提倡单向数据流,只有父组件交给子组件的数据子组件才有使用的权限,不允许子组件私自获取父组件的数据进行使用。在父与子的关系中子应当是处于一种被动关系

// 此处的this为子组件实例
this.$parent

子组件到父组件通讯

子组件到父组件的通讯主要为父组件如何接受子组件之中的数据。这里的数据包括属性和方法(String, Number, Boolean, Object, Array, Function)

通过 $emit 传递父组件数据 (推荐)

与父组件到子组件通讯中的$on配套使用,可以向父组件中触发的方法传递参数供父组件使用

<!-- 父组件 -->
<template>
    <div>
        <my-child @childEvent="parentMethod"></my-child>
    </div>
</template>

<script>
    import MyChild from '@components/common/MyChild'

    export default {
        components: {
            MyChild
        },
        data() {
            return {
                parentMessage: '我是来自父组件的消息'
            }
        },
        methods: {
            parentMethod({ name, age }) {
                console.log(this.parentMessage, name, age)
            }
        }
    }
</script>
<!-- 子组件 -->
<template>
    <div>
        <h3>子组件</h3>
    </div>
</template>

<script>
    export default {
        mounted() {
            this.$emit('childEvent', { name: 'zhangsan', age:  10 })
        }
    }
</script>

refs 获取

可以通过在子组件添加ref属性,然后可以通过ref属性名称获取到子组件的实例。准确来说这种方式和this.parent一样并不属于数据的传递而是一种主动的查找。 尽量避免使用这种方式。因为在父子组件通信的过程中。父组件是处于高位是拥有控制权,而子组件在多数情况下应该为纯视图组件,只负责视图的展示和自身视图的逻辑操作。对外交互的权利应该由父组件来控制。所以应当由父组件传递视图数据给子组件,子组件负责展示。而子组件的对外交互通过emit触发父组件中相应的方法,再由父组件处理相应逻辑

<!-- 父组件 -->
<template>
    <div>
        <my-child ref="child"></my-child>
    </div>
</template>

<script>
    import MyChild from '@components/common/MyChild'

    export default {
        components: {
            MyChild
        },
        mounted() {
            console.log(this.$refs['child'])
        }
    }
</script>
<!-- 子组件 -->
this.$refs['child']

实例

如果一个项目中有很多地方用到了同一个类型的东西, 那我们可以考虑把它做成公共组件, 便于开发和维护
如下, 很多页面就用到了这个



需求

  • 序号个数不固定, 2-4个
  • 对应页面的序号样式为蓝色, 而且要比别的大一圈, 且左右相邻的横线颜色为蓝色渐变
  • 已完成的步骤背景色为浅灰, 字体颜色为蓝色

组件

  • 子组件
<!-- 步骤 -->
<template>
    <div>
        <div class="step">
            <div class="line"></div>
            <div class="step-label" v-for="(item,index) in steps" :key="item.id">
                <div 
                    class="step-sign"
                    :class="[activeStep == index+1 ? 'step-sign-active' : '', activeStep > index+1 ? 'step-font-color' : '']">
                    {{ index+1 }}
                </div>
                <div v-if="activeStep == index+1 && steps.length == 2" :class="linePosition2(activeStep)"></div>
                <div v-if="activeStep == index+1 && steps.length == 3" :class="linePosition3(activeStep)"></div>
                <div v-if="activeStep == index+1 && steps.length == 4" :class="linePosition4(activeStep)"></div>
                <span>{{ item.name }}</span>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'step',
        props: {
            steps: {
                type: Array,
                default: [
                    // {
                    //     step: '1',
                    //     name: 'aaa'
                    // }, {
                    //     step: '2',
                    //     name: 'bbb'
                    // }, {
                    //     step: '3',
                    //     name: 'ccc'
                    // }
                ]
            },
            activeStep: {
                type: Number,
                default: 0
            }
        },
        methods: {
            // 判断位置
            linePosition2(val) {
                if (val == 1) {
                    return 'line-active2-side-left';
                } else {
                    return 'line-active2-side-right';
                }
            },
            linePosition3(val) {
                if (val == 1) {
                    return 'line-active3-side-left';
                } else if (val == this.steps.length) {
                    return 'line-active3-side-right';
                } else {
                    return 'line-active3';
                }
            },
            linePosition4(val) {
                if (val == 1) {
                    return 'line-active4-side-left';
                } else if (val == this.steps.length) {
                    return 'line-active4-side-right';
                } else {
                    return 'line-active4';
                }
            }
        },
    }
</script>

<style lang='less'>
    .step {
        position: relative;
        width: 3.75rem;
        height: 1.2rem;
        padding: 0 0.48rem;
        overflow: hidden;

        display: flex;
        justify-content: space-between;
        align-items: center;
        .line {
            position: absolute;
            width: 2rem;
            height: 0.04rem;
            background: #e8e8e8;
            top: 0.58rem;
            left: 0;
            right: 0;
            margin: auto;
            z-index: 1;
        }
        .step-label {
            position: relative;
            width: 0.7rem;
            height: 0.9rem;
            
            display: flex;
            align-items: center;
            justify-content: center;
            .step-sign {
                // position: absolute;
                width: 0.35rem;
                height: 0.35rem;
                border-radius: 50%;
                background: #ccc;
                color: #fff;
                border: 0.01rem solid #fff;
                font-size: 0.12rem;
                z-index: 9;

                display: flex;
                justify-content: center;
                align-items: center;
            }
            .line-active2-side-left {
                position: absolute;
                width: 1.8rem;
                height: 0.04rem;
                background: linear-gradient(to right,  #5eadff, #fff);
                top: 0.43rem;
                left: 0.5rem;
                z-index: 2;
            }
            .line-active2-side-right {
                position: absolute;
                width: 1.8rem;
                height: 0.04rem;
                background: linear-gradient(to left, #5eadff, #fff);
                top: 0.43rem;
                right: 0.52rem;
                z-index: 2;
            }
            .line-active3 {
                position: absolute;
                width: 1.8rem;
                height: 0.04rem;
                background: linear-gradient(to left, #fff, #5eadff, #fff);
                top: 0.43rem;
                z-index: 2;
            }
            .line-active3-side-left {
                position: absolute;
                width: 0.9rem;
                height: 0.04rem;
                top: 0.43rem;
                left: 0.4rem;
                background: linear-gradient(to left, #fff, #5eadff);
                z-index: 2;
            }
            .line-active3-side-right {
                position: absolute;
                width: 0.9rem;
                height: 0.04rem;
                top: 0.43rem;
                right: 0.4rem;
                background: linear-gradient(to right, #fff, #5eadff);
                z-index: 2;
            }
            .line-active4 {
                position: absolute;
                width: 1.2rem;
                height: 0.04rem;
                background: linear-gradient(to left, #fff, #5eadff, #fff);
                top: 0.43rem;
                z-index: 2;
            }
            .line-active4-side-left {
                position: absolute;
                width: 0.6rem;
                height: 0.04rem;
                top: 0.43rem;
                left: 0.4rem;
                background: linear-gradient(to left, #fff, #5eadff);
                z-index: 2;
            }
            .line-active4-side-right {
                position: absolute;
                width: 0.6rem;
                height: 0.04rem;
                top: 0.43rem;
                right: 0.4rem;
                background: linear-gradient(to right, #fff, #5eadff);
                z-index: 2;
            }
            .step-sign-active {
                width: 0.5rem;
                height: 0.5rem;
                font-size: 0.19rem;
                background: #5eadff;
                box-shadow: 0 0 0.1rem #5eadff;
            }
            .step-font-color {
                color: #5eadff;
                background: #f4f4f4;
            }
            span {
                position: absolute;
                bottom: 0;
                left: 0;
                right: 0;
                margin: auto;
                font-size: 0.14rem;
                color: #333;
            }
        }
    }
</style>
  • 父组件
<!-- 引用 -->
<template>
    <div>
        <BaseStep :steps="steps" :activeStep="activeStep"></BaseStep>
    </div>
</template>

<script>
    import BaseStep from '@/components/common/BaseStep.vue'

    export default {
        name: 'home',
        data () {
            return {
                steps: [
                    {
                        step: '1',
                        name: 'aaa'
                    }, {
                        step: '2',
                        name: 'bbb'
                    }, {
                        step: '3',
                        name: 'bbb'
                    }
                ],
                activeStep: 3
            }
        }
    }
</script>
相关文章
|
2天前
|
JavaScript 测试技术
vue不同环境打包环境变量处理
vue不同环境打包环境变量处理
13 0
|
2天前
|
JavaScript
vue中高精度小数问题(加减乘除方法封装)处理
vue中高精度小数问题(加减乘除方法封装)处理
12 0
|
2天前
|
JavaScript
vue项目使用可选链操作符编译报错问题
vue项目使用可选链操作符编译报错问题
8 0
|
2天前
|
JavaScript
Vue项目启动报错处理
Vue项目启动报错处理
6 1
|
2天前
|
JavaScript 定位技术
vue项目开发笔记记录(二)
vue项目开发笔记记录
30 0
|
JavaScript 测试技术 容器
Vue2+VueRouter2+webpack 构建项目
1). 安装Node环境和npm包管理工具 检测版本 node -v npm -v 图1.png 2). 安装vue-cli(vue脚手架) npm install -g vue-cli --registry=https://registry.
980 0
|
7天前
|
JavaScript 算法 Linux
【vue报错】error:0308010C:digital envelope routines::unsupported
【vue报错】error:0308010C:digital envelope routines::unsupported
34 3
|
2天前
|
JSON JavaScript API
vue项目开发笔记记录(一)
vue项目开发笔记记录
30 0
|
2天前
|
JavaScript
Vue-实现点击空白处隐藏某节点
Vue-实现点击空白处隐藏某节点
9 1
|
2天前
|
缓存 JavaScript 前端开发
vue项目实战:实战技巧总结(中)
vue项目实战:实战技巧总结
29 1