vue2自定义组件中使用v-model
vue2自定义组件中使用v-model背景v-bindv-model背景在vue中自定义组件怎么实现v-model实现数据的双向绑定,v-bind是单向数据流,因此子组件是无法修改props的值。v-bind使用v-bind通过修改参数时,事件通讯通知父节点修改参数,从而实现类似v-model功能。//child nodeVue.component('custom-input', {props:
·
背景
在vue中自定义组件怎么实现v-model实现数据的双向绑定,v-bind是单向数据流,因此子组件是无法修改props的值。
v-bind
使用v-bind通过修改参数时,事件通讯通知父节点修改参数,从而实现类似v-model功能。
//child node
Vue.component('custom-input', {
props: {
value: String
},
template: `
<input
v-bind:value="value"
v-on:change="$emit('change', $event.target.value)"
> `
})
//parent node
<template>
<div>
<custom-input
v-bind:value="inputValue"
v-on:change="handleChangeValue"
></custom-input>
</div>
</template>
<script>
export default {
data() {
inputValue: "hello"
},
methods:{
handleChangeValue(e){
this.inputValue=e;
}
}
}
</script>
v-model
vue2.2.0+ 新增了v-model配置(在vue3中移除了)
注意:一个标签里面有且只能有一个 v-model
//child node
Vue.component('custom-input', {
model: {
prop: 'value',
event: 'change'
},
props: {
value: String
},
template: `
<input
v-bind:value="value"
v-on:change="$emit('change', $event.target.value)"
>
})
//parent node
<template>
<div>
<custom-input v-model="inputValue"></custom-input>
</div>
</template>
<script>
export default {
data() {
inputValue: "hello"
}
}
</script>
详情请看官网地址:vue2 自定义事件 v-model
更多推荐
已为社区贡献3条内容
所有评论(0)