如何正确将v-model传递给Quasar q-input基础组件?

9
我正在使用Quasar构建我的Vue应用程序,并希望使用q-input创建基础组件(又称表示、哑或纯组件)。
我已经创建了一个名为VInput.vue的SFC作为我的基础组件,它看起来像这样:
<template>
  <q-input
    outlined
    class="q-mb-md"
    hide-bottom-space
  />
</template>

然后我创建了一个名为TestForm.vue的SFC,它看起来像这样:

<template>
  <q-form>
    <v-input label="Email" v-model="email" />
  </q-form>
</template>

<script setup lang="ts">
import VInput from './VInput.vue';
import { ref } from 'vue';
const email = ref('john@example.com');
</script>

"

label="Email" v-model="email" 部分被传递到我的 VInput.vue 基础组件,并在页面上正确呈现。

但是,在 VInput.vue 基础组件的 q-input 上存在 TypeScript 错误,因为 q-input 需要一个 v-model:

"
`Type '{ outlined: true; class: string; hideBottomSpace: true; "hide-bottom-space": boolean; }' is not assignable to type 'IntrinsicAttributes & VNodeProps & AllowedComponentProps & ComponentCustomProps & QInputProps'.`
`Property 'modelValue' is missing in type '{ outlined: true; class: string; hideBottomSpace: true; "hide-bottom-space": boolean; }' but required in type 'QInputProps'.ts(2322)`.

那么,如果我不事先知道v-model的值,该如何编写VInput.vue基础组件呢?
我想出了下面的解决方案,似乎可以工作,因为我认为传递下来的v-model会覆盖基础组件的v-model。
但我想问一下,以确保我没有搞砸。
这是正确的做法吗?它看起来有些hacky。
<template>
  <q-input v-model="inputText" outlined class="q-mb-md" hide-bottom-space />
</template>

<script setup lang="ts">
const inputText = '';
</script>
1个回答

10

我找到了几个解决方案:

解决方案 1

该方案涉及将 v-model 拆分为其各个部分(:model-value@update:model-value),然后将文本值作为 prop 传入。

基础组件 VInput.vue

    <template>
      <q-input
        outlined
        class="q-mb-md"
        hide-bottom-space
        :model-value="text"
        @update:model-value="(value) => emit('update:text', value)"
      />
    </template>
    
    <script setup lang="ts">
    defineProps({
      text: {
        required: false,
        type: String,
      },
    });
    const emit = defineEmits(['update:text']);
    </script>

解决方案 2

提取属性并在其上使用toRef

    <template>
      <q-input outlined class="q-mb-md" hide-bottom-space v-model="textProp" />
    </template>
    
    <script setup lang="ts">
    import { toRef } from 'vue';
    const props = defineProps({
      text: {
        required: false,
        type: String,
        default: '',
      },
    });
    const textProp = toRef(props, 'text');
    </script>

解决方案1运行良好;我无法使解决方案2运行起来;我得到的错误信息是:"在键“text”上执行设置操作失败:目标是只读的"(我按照您的建议使用了v-model="textProp")。这是在Vue 3.2.x版本下发生的;我没有使用TypeScript,但我不认为这是问题所在? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接