自定义组件支持双向绑定的实现
假设有这样一个单文件组件:CustomerInput.vue,其内容如下:
<template>
<div>
<input class="commafy-input__inner" 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);
width: 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>
这样就实现了简单的双向绑定了。
阅读是一种修养,分享是一种美德。

浙公网安备 33010602011771号