v-model实现数据双向绑定,其实现原理为:
:value=“params” @input=“params = $event.target.value”(v-model语法糖)
自己写了个demo,代码如下:
父组件
在这<template>
<div>
<testChild v-model="testText"></testChild>
</div>
</template>
<script>
import testChild from '@/common/components/test-child.vue'
export default {
name: 'Test',
data() {
return {
testText: '123'
}
},
components: {
testChild
},
watch: {
testText() {
console.log(this.testText)
}
}
}
</script>里插入代码片
子组件:
在<template>
<div>
<!-- input事件,blur事件,change事件都可以 -->
<input type="text" v-model="currentValue" @input="inputEvent">
</div>
</template>
<script>
export default {
data() {
return {
currentValue: ''
}
},
props: {
value: [String, Number]
},
watch: {
value() {
this.currentValue = this.value
}
},
created() {
this.currentValue = this.value
},
methods: {
inputEvent() {
this.$emit('input', this.currentValue)
}
}
}
</script>这里插入代码片
在一个组件上使用 v-model 时,会简化为:
<custom-input
:value=“something”
@input=“value => { something = value }”>
因此,对于一个带有 v-model 的组件,它应该如下:
接收一个 value prop
触发 input 事件,并传入新值
利用 $emit 触发 input 事件:
this.$emit(‘input’, value);
参考文章:参考文章