vue 使用computed拦截v-model

426 阅读1分钟

vue 使用computed拦截v-model

  1. 子组件必须接受一个 value 属性作为 prop,并在需要的地方使用它来获取父组件传递过来的值。
  2. 子组件中通过监听输入事件(如按钮点击、选择变化等)来改变内部的值,并使用 $emit('input', newValue) 来触发 v-model 绑定的更新。

下面是一个示例:

父组件:

<template>
  <categoryFilter v-model="categoryType" />
</template>

<script>
export default {
  data() {
    return {
      categoryType: ''
    }
  }
}
</script>

子组件:

<template>
  <v-btn-toggle v-model="internalValue" ...>
    ...
  </v-btn-toggle>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      required: true
    }
  },
  computed: {
    // 关键在这,利用计算属性的get set 进行拦截
    internalValue: {
      get() {
        return this.value;
      },
      set(newValue) {
        this.$emit('input', newValue);
      }
    }
  }
}
</script>