【问题标题】:Vue v-model on input as a dynamic refVue v-model 在输入上作为动态参考
【发布时间】:2021-09-01 13:49:40
【问题描述】:

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

【问题讨论】:

    标签: html vue.js vue-composition-api


    【解决方案1】:

    我认为您只需要在 clearValue 函数内发出具有空值的“输入”事件

    emit('input', '');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 2018-06-13
      • 2018-11-10
      • 2020-08-19
      • 2019-04-30
      • 2019-03-16
      • 2020-10-29
      相关资源
      最近更新 更多