为了账号安全,请及时绑定邮箱和手机立即绑定

VUE手写input组件

标签:
Vue.js

在写带有input的组件时,如果没有任何处理直接写的话,看似也是写出来了,但是在调用的时候,无法获取、绑定到input中的值,辛苦大半天,写了一个废物,然后处理之后是这个样子。

CellInput.vue 组件

<template>
    <div class="cellInput">
        <li class="input_1 ">
            <p>{{cell_title}}</p>
            <input
                type="text"
                :placeholder="cell_plachd"
                maxlength="25"
                ref="input"
                :value="value"
                @input="$emit('input',$event.target.value)"
            >
        </li>
    </div></template><script>export default {    props:{        cell_title:String,        cell_plachd:String,        value:String,
    },
}</script><style lang="scss" scoped>.cellInput{
    width: 100%;
    background: #fff;
    .input_1{
        width: 100%;
        height: 1.64rem;
        padding: 0.5rem 0 0.5rem 0rem;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        align-content: space-between;
        position: relative;
        p{
            width: 4rem;
            height: 0.64rem;
            font-size: 0.6rem;
            line-height: 0.64rem;
            color: #34304b;
            margin-left: 0.8rem;
        }
        input{
            border:none;
            width: 9rem;
            height: 0.64rem;
            font-size: 0.6rem;
            text-align: right;
            margin-left: 1.4rem;
            margin-right: 1.54rem;
        }
        div{
            width: 0.26rem;
            height: 0.46rem;
            background:url(./../../assets/img/css2.png) no-repeat -0.64rem -1.32rem;
            background-size: 1.56rem 19rem;
            margin-left: 0.5rem;
        }
    }
}</style>

然后做一个全局注册

import CellInput from "./CellInput.vue";const components = {    install: function (Vue) {
        Vue.component('CellInput', CellInput);
    }
}export default components;

调用

<template>
    <div class="addMachine" >
        <CellInput
            cell_title="设备ID"
            cell_plachd="请填写或扫码设备ID"
            v-model="ID"
        ></CellInput>
    </div></template><script>export default {
    data(){        return{            // 添加店铺数据
            ID:'112345',
        }
    },
}

这就完事了,不过在定义组件的代码里面,有这么一句 @input="$emit('input',$event.target.value)",想必这就是整个组件中的难点了,至于为什么要这么写,这其实就涉及到了 v-model的用法极其背后的所有相关知识,有一篇文章我觉得写得挺不错,可以直接参考:Vue 进阶教程之:详解 v-model



作者:刘员外__
链接:https://www.jianshu.com/p/1710621194d8


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消