Vue_07(组件的v-model)

v-model | Vue.js https://v3.cn.vuejs.org/guide/component-custom-events.html#v-model-%E5%8F%82%E6%95%B0

在input中可以使用v-model来完成双向绑定

<input v-model="message">
 #上下等同
<input :value="message" @input="message = $event.target.value">

vue也支持在组件上使用v-model

<hy-input v-model="message"></hy-input>
#上下等同
<hy-input :modelValue="message" @update:model-value="message = $event"></hy-input>

组件v-model的实现

<template>
  <div>
    <input :value="modelValue" @input="btnClick">
  </div>
</template>

<script>
  export default {
    props: ['modelValue'],
    emits: ["update:modelValue"],
    methods: {
      btnClick(event) {
        this.$emit("update:modelValue", event.target.value);
      }
    }
  }
</script>

<style scoped>

</style>

利用computed实现(更佳)

<template>
  <div>
    <input v-model="value">
    <input v-model="why">
  </div>
</template>

<script>
  export default {
    props: {
      modelValue: String,
      title: String 
    },
    emits: ["update:modelValue", "update:title"],
    computed: {
      value: {
        set(value) {
          this.$emit("update:modelValue", value);
        },
        get() {
          return this.modelValue;
        }
      },
      why: {
        set(why) {
          this.$emit("update:title", why);
        },
        get() {
          return this.title;
        }
      }
    }
  }
</script>

<style scoped>

</style>

  

上一篇:【Rust】打开文件


下一篇:Why OpenMetadata is the Right Choice for you