菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
51
0

自定义组件实现v-model双向数据绑定

原创
05/13 14:22
阅读数 1261

我们都清楚v-model其实就是vue的一个语法糖,用于在表单控件或者组件上创建双向绑定。

//表单控件上使用v-model
<template>
    <input type="text" v-model="name" />
    <input type="checkbox" v-model="checked"/>
    <!--上面的input和下面的input实现的效果是一样的-->
    <input type="text" :value="name" @input="name=e.target.vlaue"/>
    <input type="checkBox" :checked="checked" @click=e.target.checked/>
    {{name}}
</template>
<script>
export default{
    data(){
        return {
            name:"",
            checked:false,
        }
    }
}
</script>

vue中父子组件的props通信都是单向的。父组件通过props向下传值给子组件,子组件通过$emit触发父组件中的方法。所以自定义组件是无法直接使用v-model来实现v-model双向绑定的。那么有什么办法可以实现呢?

//父组件
<template>
  <div>
   <c-input v-model="form.name"></c-input>
   <c-input v-model="form.password"></c-input>
   <!--上面的input等价于下面的input-->
  <!--<c-input :value="form.name" @input="form.name=e.target.value"/>
   <c-input :value="form.password" @input="form.password=e.target.value"/>-->
  </div>
</template>
<script>
import cInput from "./components/Input"
export default {
  components:{
   cInput
  },
  data() {
    return {
      form:{
        name:"",
        password:""
      },
      
    }
  },
}
</script>
//子组件 cInput
<template>
    <input type="text" :value="inputValue" @input="handleInput">
</template>
<script>
export default {
  props:{
    value:{
      type:String,
      default:"",
      required:true,
    }
  },
  data() {
    return {
      inputValue:this.value,
    }
  },
  methods:{
    handleInput(e){
      const value=e.target.value;
      this.inputValue=value;
      this.$emit("input",value);
    },
  }
}
</script>

根据上面的示例代码可以看出,子组件c-input上绑定了父组件form的值,在子组件中通过:value接收了这个值,然后我们在子组件中修改了这个值,并且通过$emit触发了父组件中的input事件将修改的值又赋值给了form。
综上就实现了自定义组件中的双向数据绑定!

发表评论

0/200
51 点赞
0 评论
收藏
为你推荐 换一批