以下会在input、checkbox、select、div组件上分别实现双向绑定:

input

在input组件上绑定v-model指令,实现双向绑定:

实现思路:

为input 框动态绑定父级传过来的值getedValue ,子组件触发input原生事件时,获取到输入框中的值,通过$emit发送给父组件,在父组件修改,在传给子组件:

<!-- news_son.vue -->
<template>
<div>
<h1>组件的双向绑定</h1>
<input type="text" :value="getedValue" @input="$emit('input', $event.target.value)">
</div>
</template>
<script>
export default {
props: {getedValue : String}
}
</script>
<!-- news_father.vue -->
<!--<lv-input :getedValue="val" @input="val=arguments[0]"></lv-input>-->
<template>
<div>
<lv-input v-model="val"></lv-input>
</div>
</template>

checkbox组件的双向绑定

<template>
<input @change="$emit('change', $event.target.checked)" :checked="checked" type="checkbox">
</template>
<script>
export default {
model: {
prop: 'checked',
event: 'change'
},
props: {checked: Boolean}
}
</script>
// 在父组件中
<checkbox-com v-model="xxx">

 

select 组件的双向绑定

<template>
<div>
<select :value="value" @change="change">
<option :value="1">1</option>
<option :value="2">2</option>
</select>
</div>
</template>
<script>
export default {
model: {
prop: 'value',
event: 'change'
},
props: {value: Number},
methods: {
change(e) {
this.$emit('change', e.target.value)
}
}
}
</script>

 

自定义div组件的双向绑定

<template>
<div>
<div @click="handleDiv">
<span>click</span>
<h5>{{i}}</h5>
</div>
</div>
</template>
<script>
export default {
mode: {
prop: 'value',
event: 'input'
},
props: {
value: Number
},
data() {
return {
i: this.value
}
},
methods: {
handleDiv() {
this.i ++
this.$emit('input', this.i)
}
}
}
</script>
// 在组件中调用
<div-com v-model="xxx"/>