Vue组件使用v-model

本文详细解析了Vue.js框架中v-model指令的工作原理,包括在普通元素及组件间如何实现双向数据绑定。通过示例代码,读者可以深入了解v-model在不同场景下的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看下简单的,在一个页面中使用 v-model 进行 双向数据绑定


<input type="text" v-model="textValue">
<h1>{{ textValue }}</h1>

相信这行代码,大家肯定都非常熟悉!官方文档说明了 v-model 其实如如下原理:

<input type="text"
  v-bind:value = "textValue"
  v-on:input = "textValue = $event.target.value"
>
<h1>{{ textValue }}</h1>

组件上使用v-model:

//父组件 templateParant.vue

<template>
  <div>
    <template-child v-model="textValue"></template-child>

    <!-- <template-child
      v-bind:value = "textValue"
      v-on:input = "textValue = $event"
    ></template-child> -->

    <!--  这两种写法是等价的,至于 v-on:input = "textValue = $event" 
为什么是 $event而不是$event.target.value,这是一个值得思考的问题 -->
    <div>{{ textValue }}</div>
  </div>
</template>
<script>
import templateChild from './templateChild '

export default {
  
  data() {
    return {
      textValue: ''
    }
  },
  components: {
    modelChild
  },
  mounted() {
    
  }
};
</script>
<style scoped>
</style>

//  子组件templateChild.vue

<template>
  <div>
    输入<input type="text"  
      v-bind:value="value"
      v-on:input="$emit('input',$event.target.value)"
    >
  </div>
</template>
<script>
export default {
  props: ['value'],    //子组件用一个props接住父组件传进来的value属性值,然后在自己的input绑定该值,并且使用$emit向父组件通信,传递input事件和input输入的值($event.target.value),在父组件v-model既可以实现与子组件的双向数据绑定了。
  data() {},
  components: {

  },
  mounted() {
    
  }
};
</script>
<style scoped>
</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值