Vue之 v-model 数据的双向绑定

一、v-model 的使用范围

v-model 官网解释。

图片

二、v-model 基本用法

 谈及Vue ,都会说到MVVM(Mode-View-View-Model)双向绑定。v-model 就是个很好的证明,input 输入的值,会立即显示到 span 上,

<template>
  <div>  
    <input type="text" v-model="age" />
    <br/>
    <span>{{age}}</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      age: 0,
    }
  },
};
</script>

<style>
</style>

三、v-model 的实质


<template>
  <div>  
    <input type="text" :value="age" @input="age = $event.target.value" />
     <br/>
    <span>{{age}}</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      age: 0,
    }
  },
  methods:{
    enter(e){
      console.log(e);
    }
  }
};
</script>

<style>
</style>

四、自定义组件(Input) v-model 双向绑定

父组件:

  • 定义了 value属性:用来传递值 给子组件;
  • 定义了事件 input ;
<template>
  <div>  
    <MyInput :value="age" @input="age = $event"></MyInput>
    <span>父组件:{{age}}</span>
  </div>
</template>

<script>
import MyInput from './MyInput.vue';

export default {
  components:{
    MyInput,
  },
  data() {
    return {
      age: 'er',
    }
  },
};
</script>

<style>
</style>

子组件:

  • 相应的props接收父组件传递过来的值,value

<template>
  <div>
    子组件:
    <!-- <input :value="value" @input="$emit('input',$event.target.value)"> -->
   <!-- 两者效果相等 -->
    <input :value="value" @input="handlerInput">
  </div>
</template>

<script>
export default {
  props:{
    value:String,
  },
  methods:{
    handlerInput(e){
      // input 要与父组件定义的事件 同名;
      this.$emit('input',e.target.value);
    }
  }
  
}
</script>

<style>

</style>

五、自定义check组件 v-model

父组件核心代码:


	<!-- <MyCheckBox v-model="check"></MyCheckBox> -->
    <MyCheckBox :checked="check" @change="check = $event"></MyCheckBox>
    

子组件:

<template>
  <div>
     子组件:
     <input type="checkbox" :checked='checked' @change='handlerChange'>你今天开心嘛?
  </div>
</template>

<script>
export default {
  // model:{
  //   prop:'checked'
  // },
  props:['checked'],
  methods:{
    handlerChange(e){
      this.$emit('change',e.target.checked);
    }
  }
}
</script>

<style>

</style>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值