用户登录
用户注册

分享至

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

  • 作者: 淡然27112971
  • 来源: 51数据库
  • 2021-09-21

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

软件
前端设计
程序设计
Java相关