1.问题的产生
二次封装view UI的Input组件的时候,实现父子组件的v-model双向绑定:
//父组件
<search :searchKey.sync="project_name"
enterButton="搜索项目"
placeholder="输入你感兴趣的项目名或关键字" />
//子组件
<template>
<div>
<Input search
:enter-button="enterButton"
:placeholder="placeholder"
v-model="key" />
</div>
</template>
<script>
export default {
props:["searchKey","enterButton","placeholder"],
data(){
return {
key:this.searchKey
}
}
}
</script>
即 实现父组件中的project_name与子组件中的key双向绑定
因为searchKey是props传下来的,所以我们不能直接
v-model="searchKey"
,只能重新定义一个key用于双向绑定。在二次封装Input组件的时候,我们知道输入框绑定的实际上是子组件的key值,所以在输入框输入内容的时候实际上是更改的子组件内的key值,而我们想实现的是同时更新父组件的project_name的值。
2.解决办法
我们通过给父组件绑定的属性searchKey键添加.sync修饰符,然后在子组件内利用watch监听key与searchKey的变化:
- 监听searchKey:如果父组件修改了project_name的值则searchKey会发生变化然后更新key的值。
- 监听key:如果通过输入框输入内容则子组件的key值会发生变化然后通过
this.$emit('update:searchKey',value)
更新父组件project_name的值。
//子组件
watch:{
searchKey(value){
this.key = value;
},
key(value){
this.$emit("update:searchKey",value);
}
},