Vue基础之组件通信(2)父子组件传值:自定义组件的v-model、.sync方式

自定义组件的v-model

Vue中很常用的v-model,一般我们都使用在input标签上,实现数据的双向绑定,这也是vue一个很大的特点。实际上,v-model是一个语法糖,相当于在标签上使用了value属性和input的事件,内部实现了数据的更新。
按照官方的释义一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件,但是像单选框、复选框等类型的输入控件可能会将 value attribute 用于不同的目的。
也就是在一个组件上使用了v-bind和v-on 实现父子组件传输的数据的双向绑定。

  • 用法
    父组件
<template>
  <div class="Dad">
    <div>info:{{ info }}</div>
    <child v-model="info"></child>
  </div>
</template>
<script>
export default {
	data() {
    	return {
      		info: 1
    	}
	}
}
</script>

子组件

<template>
  <div>
    <input
      type="text"
      :value="value"
      @change="$emit('input', $event.target.value)"
    />
    <!-- <input type="text" :value="text2" @change="inputChange2" /> -->
  </div>
</template>
<script>
export default {
	props: {
    	value: {
      		default: 0
    }
}
</script>

父组件的 info的值默认会传入子组件这个名为 valueprop(还是需要在props中接收),同时当触发一个input事件时,会让info更新。

  • 效果

Vue基础之组件通信(2)父子组件传值:自定义组件的v-model、.sync方式_第1张图片
当子组件中的input更新时,父组件中的info,也就是绑定给子组件的值,也会更新。
Vue基础之组件通信(2)父子组件传值:自定义组件的v-model、.sync方式_第2张图片

.sync方式

在某些情况下,我们可能需要在组件上绑定多个数据,而v-model只能在一个组件上使用一次,这时可以用.sync方式,它提供了和v-model相同的效果,且可以绑定多个。

  • 用法
    子组件上this.$emit('update:title', newTitle)
    父组件上操控子组件
<text-document
  v-bind:title="doc.title"
  v-on:update:title="doc.title = $event"
></text-document>

为了方便,使用.sync修饰符

<text-document v-bind:title.sync="doc.title"></text-document>
  • 示例 (为做比较,和v-model同时使用)
    父组件
<template>
  <div class="Dad">
    <h2>Dad.vue</h2>
    <div>传入子组件info的值:{{ info }}</div>
    <div>传入子组件info2的值:{{ info2 }}</div>
    <child v-model="info" :value2.sync="info2"></child>//子组件
  </div>
</template>
<script>
export default {
  data() {
    return {
      info: 1,
      info2: 2,
    };
  },
</script>

将info、info2的值用两种方式传入子组件

子组件

<template>
  <div class="child">
    <h1>子组件</h1>
    <input
      type="text"
      :value="value"
      @change="$emit('input', $event.target.value)"
    />
    <input
      type="text"
      :value="value2"
      @change="$emit('update:value2', $event.target.value)"
    />
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  props: {
    value: {
      default: ""
    },
    value2: {
      default: ""
    }
  },
};
</script>
  • 效果
    Vue基础之组件通信(2)父子组件传值:自定义组件的v-model、.sync方式_第3张图片
    子组件的值变化后,父组件内也会变化。
    Vue基础之组件通信(2)父子组件传值:自定义组件的v-model、.sync方式_第4张图片
  • 小结
    使用方法基本一致,需要多个数据双向绑定时使用.sync修饰符。

你可能感兴趣的:(vue,vue)