组件通信——sync修饰符

246 阅读1分钟

sync修饰符

  • 在Vue中,sync 修饰符已经被废弃了。在 Vue 2.x 版本中,可以通过使用 v-model 来实现父子组件之间的双向绑定。而在 Vue 3.x 版本中,v-model 的使用方式也有所改变。

  • 以下是在 Vue 2.x 中实现父子组件之间的双向绑定的示例:

<!-- 子组件 Child.vue -->
<template>
  <div>
    <input type="text" :value="value" @input="$emit('update:value', $event.target.value)">
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      required: true
    }
  }
}
</script>

<!-- 父组件 Parent.vue -->
<template>
  <div>
    <Child :value.sync="message"></Child>
    <p>Message: {{ message }}</p>
  </div>
</template>

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

export default {
  data() {
    return {
      message: 'Hello Vue!'
    }
  },
  components: {
    Child
  }
}
</script>
  • 在这个示例中,子组件 Child.vue 中的 input 元素通过 :value 绑定到父组件传递的 value 属性。在子组件中,通过 $emit('update:value', $event.target.value) 触发 update:value 事件并传递输入的值。父组件中的 Child 组件通过 :value.sync 语法绑定到 message 属性,这样父组件中的 message 会随着子组件中输入框的值的改变而更新。

原理解析

  1. 子组件接收 value 属性作为 prop:
<!-- 子组件 Child.vue -->
<template>
  <div>
    <input type="text" :value="value" @input="updateValue($event.target.value)">
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      required: true
    }
  },
  methods: {
    updateValue(newValue) {
      // 触发 update:value 事件,并将新值作为参数传递
      this.$emit('update:value', newValue);
    }
  }
}
</script>
  1. 父组件使用 :value.sync 将父组件的属性与子组件的值进行绑定:
<!-- 父组件 Parent.vue -->
<template>
  <div>
    <Child :value.sync="message"></Child>
    <p>Message: {{ message }}</p>
  </div>
</template>

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

export default {
  data() {
    return {
      message: 'Hello Vue!'
    }
  },
  components: {
    Child
  }
}
</script>
  1. 在这个示例中,父组件中的 Child 组件使用了 :value.syncmessage 属性传递给子组件,并且随着子组件中输入框的值的改变而更新。
  2. 子组件中的输入框通过 :value="value" 将父组件传递的值绑定到输入框的 value 属性上,并通过 @input="updateValue($event.target.value)" 监听输入框的输入变化,调用 updateValue 方法。
  3. updateValue 方法中,子组件通过 this.$emit('update:value', newValue) 触发一个名为 update:value 的自定义事件,并将新的值作为参数传递。
  4. 父组件中监听子组件触发的 update:value 事件,并更新父组件的属性或状态,确保父组件中的数据与子组件的值保持同步。
  5. 通过这种方式,父组件和子组件之间建立了一个双向的数据绑定关系。