自定义组件支持双向绑定的实现

摘要:
假设有这样一个文件组件:CustomerInput.vue,其内容如下:exportdefault{name:'CustomerInput',mod

  假设有这样一个单文件组件:CustomerInput.vue,其内容如下:

<template>
    <div>
        <input   v-bind:value="value" v-on:input=$emit('input', $event.target.value)""></input>
    </div>
</template>

<script>
export default {
    name: 'customer-input',
    model: {
        prop: 'value',
        event: 'input'
    },
    props: {
        value: {
            type: String,
            default: ''
        }
    }
}
</script>

<style scoped>
. customer-input__inner {
    background-color: #fff;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    box-sizing: border-box;
    color: #606266;
    display: inline-block;
    font-size: inherit;
    height: 32px;
    line-height: 32px;
    padding: 0 15px;
    transition: border-color .2s cubic-bezier(.645,.045,.355,1);
     100%;
}
</style>

  那么在其它单文件组件中使用该组件时,可以这样使用:

<template>
   <div>
      <customer-input v-model="value" />
   </div>
</template>

<script>
import CustomerInput from 'CustomerInput.vue' // 或者 import CustomerInput from 'CustomerInput'
export default{
   // 第一种写法
   components: {
        CustomerInput
   }
   // 第二种写法
   //components: {
   //     'customer-input': CustomerInput
   //}
   data() {
      return {
          value: ''
      }
   }
}
</script>

<style>
</style>

  这样就实现了简单的双向绑定了。

免责声明:文章转载自《自定义组件支持双向绑定的实现》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇vscode+vue不得不用的插件和不得不添加的配置数据库中varchar类型数据转换为numeric类型下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

js实现全选和取消全选

HTMl      <input type="checkbox" name="allCheckBox" />      <br/>       <input type="checkbox" name="checkbox" />        <input type="checkbox" name="checkb...

如何监听input的脚本赋值

今天记录下我解决input值改变监听,大家肯定首先想到onchange方法。对于实时监听改变用onpropertychange、oninput等方法;可是,onchange并不能监听脚本改变的值,对于onpropertychange也只能实现IE监听并不兼容所有浏览器问题; 想了好久,我找到了一个很好的方法,借此跟大家分享一二: 假设 html:<i...

iptables详解之filter

iptables详解之filter iptables令很多小伙伴脑阔疼,下面我们来说说如何使用iptables。 一、iptables格式 1.1、iptables 帮助 通过iptables --help查看一下iptables用法 [root@note1 ~]# iptables --help iptables v1.4.21 Usage: ipta...

前端用js获取本地文件的内容

这里要写成input的形式 调用upload函数 传递的参数就表示所选的文件<input type="file" onchange="upload(this)" /> //前端读取本地文件的内容 下面代码中的this.result即为获取到的内容 function upload(input) { //支持chrome IE10...

微信小程序-获取input值的两种方法

1、bindinput <input bindinput='getInputValue' name='price' type='text' placeholder='输入内容'></input> 其中e.detail是获取input数据 其中包含value值,cursor是获取光标的位置。 getInputValue(e){...

vue 移动端车牌键盘

1.npm install input-plate-number --save 样式可以,键盘相对严谨,但是输入有bug, 2.npm installvue-carplate --save 插件样式个人看来是最好看的,键盘的输入最严谨,但是没有新能源车牌的选项, 3.https://github.com/Pinenutss/LicensePlate 插件是...