在写带有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