输入的 Vue v-model 作为动态引用

Vue v-model on input as a dynamic ref

我创建了这个 <input> Vue 组件来处理 v-model 属性。 添加双向数据绑定不是问题,但我现在想将当前输入值添加到“状态”,这样我就可以通过修改 ref.

来清除它

clearValue 按预期调用,但更新 inputValue 不会更新 UI。我应该做些什么不同的事情?

<template>
  <div>
    <input
      :id="id"
      type="text"
      :value="inputValue"
      @input="updateValue"
    />
    <UiIcon
      type="x"
      @click.native="clearValue"
    />
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref } from '@nuxtjs/composition-api';
import UiIcon from '~/components/ui/UiIcon.vue';

export default defineComponent({
  name: 'UiInput',
  components: { UiIcon },
  props: {
    id: {
      type: String,
      required: true,
    },
    value: {
      type: String,
      default: undefined,
    },
  },
  setup(props, { emit }) {
    const inputValue = ref(props.value);

    const clearValue = () => {
      inputValue.value = '';
    };

    const updateValue = (event: Event) => {
      emit('input', (event.target as HTMLInputElement).value);
    };
  
    return {
      updateValue,
      clearValue,
      inputValue,
    };
  },
});

用法示例

data() {
  return { text: '' };
},
template: `
  <div>
    <UiInput :id="id" v-model="text" />
  </div>
`,

我认为您只需要在 clearValue 函数

中发出带有空值的 'input' 事件
emit('input', '');