vue自己编写封装一个简单的组件

闲来无聊,自己写一个简单的步进器组件。

新建目录/页面目录结构

把一个.vue页面分为三个部分
Tql.vue只写页面的html结构

stepper,js只写页面的用户交互/逻辑部分

stepper.less只写页面的表现样式部分

--stepper
----stepper.js
----stepper.less
----Tql.vue

在components下新建自定义组件


<template>
    <div>
        步进器
    div>
template>

<script>
export default {
}

script>
<style lang='less' scoped>
}
style>

stepper.js

页面的逻辑部分

// 引入组件stepper组件
import stepper from "../../components/stepper.vue";

export default {
    data () {
        return {
            propsteppervalue: 0
        }
    },
    // 注册局部组件
    components: {
        stepper
    },
    methods: {
        // 被动调用的方法,用来接收子组件传的值
        stepperValue (value) {
            this.propsteppervalue = value
        }
    }
}

Tql.vue

页面的html结构部分

<template>
    
    
    <stepper 
        :propvalue="propsteppervalue" v-on:emitStepper="stepperValue"
    >
    stepper>
template>

<script>
import stepper from "./stepper";
export default stepper
script>

<style lang="less" scoped>
@import url('./stepper.less');
style>

stepper component 具体


<template>
    <div>
        <div class="stepper__main">
            <button class="stepper__main-add" @click="addSteppernum">+button>
            <input type="text" v-model="num">
            <button class="stepper__main-cut" @click="cutSteppernum">-button>
        div>
    div>
template>

<script>
export default {
    // 接收父组件中传来的值
    props: {
        propvalue: {
            type: Number,
            // 如果传值为空,默认为0
            default: 0
        }
    },
    data () {
        return {
            num: null
        };
    },
    created () {
        const _this = this
        // props接收的值赋值给子组件内部的值
        _this.num = this.propvalue
    },
    methods: {
        // 不能在子组件中修改父组件的值
        cutSteppernum () {
            if (this.num === 0) {
                return
            }
            this.num = --this.num
            // 组件之间传值。子传父
            this.$emit('emitStepper', this.num)
        },
        addSteppernum () {
            this.num = ++this.num
            this.$emit('emitStepper', this.num)
        }
    }
}

script>
<style lang='less' scoped>
@background: #ccc;

.stepper__main {
    position: relative;
    width: 500px;
    height: 200px;
    margin: 0 auto;
    top: 50px;
    input {
        display: inline-block;
        box-sizing: border-box;
        padding-left: 20px;
        width: 200px;
        height: 50px;
        margin: 0 20px;
        font-size: 24px;
    }
    button {
        appearance: none;
        width: 50px;
        height: 50px;
        outline: none;
        cursor: pointer;
        font-size: 20px;
        border-radius: 10px;
        &:hover {
            color: rgb(119, 173, 245);
        }
    }
    .stepper__main-add {
        display: inline-block;

    }
}
style>

为什么在子组件内部不能修改父组件传来的值呢?因为子组件的值跟父组件的值互相有联系。父组件的值改变了子组件的值也会发生改变。反之亦然。

你可能感兴趣的:(组件,传值,component)