Vue的v-model自定义组件
一个组件上的 v-model
默认会利用名为 value
的 prop 和名为 input
的事件,但是像单选框、复选框等类型的输入控件可能会将 value
特性用于不同的目的。model
选项可以用来避免这样的冲突
先来个默认的代码:
子组件:
<template>
<div id="son">
这是子组件:<input :value="value" @input="$emit('input',$event.target.value)"></input>
<!--v-model默认绑定的组件的属性是value,事件是input-->
</div>
</template>
<script>
export default {
name: "Son",
props: ['value'],
//props需要填value,为input的value属性,因为父组件model默认绑定的就是input的value属性
//如果写其他字段,父组件无法传值到子组件
}
</script>
<style scoped>
</style>
然后是父组件:
<template>
<div id="father">
<son v-model="msg"></son>
<!--一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件,-->
这是父组件:<input v-model="msg">
</div>
</template>
<script>
import Son from "./Son"
export default {
components: {
Son,
},
name: 'Father',
data() {
return {
msg: '默认',
}
}
}
</script>
<style scoped>
</style>
最后上效果: 实现双向绑定,任意一个输入框输入都会同步
然后我们来用model
改写
子组件:
<template>
<div id="son">
这是子组件:<input :value="newValue" @input="$emit('newEvent',$event.target.value)"></input>
<!--v-model默认绑定的组件的属性是value,事件是input-->
<!--这里我们改为newValue和newEvent-->
</div>
</template>
<script>
export default {
name: "Son",
model: {
prop: "newValue",
event: 'newEvent'
},
props: ['newValue'],
//现在props需要填newValue,input绑定的就是newValue,父组件的值传入进来,再input上显示
//如果写其他字段,父组件无法传值到子组件
}
</script>
<style scoped>
</style>
父组件:
<template>
<div id="father">
<son v-model="msg"></son>
<!--一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件,-->
<!--这里我们改为newValue和newEvent-->
这是父组件:<input v-model="msg">
</div>
</template>
<script>
import Son from "./Son"
export default {
components: {
Son,
},
name: 'Father',
data() {
return {
msg: '默认',
}
}
}
</script>
<style scoped>
</style>
两者效果是一样的: