网络编程 
首页 > 网络编程 > 浏览文章

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

(编辑:jimmy 日期: 2024/5/20 浏览:3 次 )

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

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

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

上一篇:js实现移动端吸顶效果
下一篇:微信小程序实现吸顶效果
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网