vue.js自定义组件实现v-model双向数据绑定的代码实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue.js自定义组件实现v-model双向数据绑定的代码实例

  2021-04-02 我要评论

我们都清楚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。

综上就实现了自定义组件中的双向数据绑定!

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们