相思资源网 Design By www.200059.com

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

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

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

标签:
vue.js,v-model双向数据绑定,vue.js,双向数据绑定

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

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

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