vuejs3

How to forward v-model modifiers to child component


No idea on how to forward the v-model modifiers received by a wrapper component to a child component or element...

Sample App:

<script setup lang="ts">
import MementoField from './MementoField.vue'
import { ref } from 'vue'

const value = ref("hello, world")
</script>

<template>
  <MementoField v-model="value" />
  <br/>
  <MementoField v-model.lazy="value" />
  <br/>
  <span>Lazy: </span>
  <input v-model.lazy="value" />
</template>

Component MementoField.vue:

<script setup lang="ts">

const [model, modifiers] = defineModel<string>({ default: ''})
// how to forward modifiers to <input> child element ?

const memento = model.value

</script>

<template>
  <div>
    <div>Initial value: {{ memento }}</div>
    <div>Current value: {{ model }}</div>
    <input v-model="model" @keydown.esc="model = memento">
    <span> (ESC to reset)</span>
  </div>
</template>

Link to SFC Playground

I didn't found a generic solution (supporting custom modifiers)


Solution

  • You can use manual rendering with withDirectives:

    Playground

        <component 
          :is="withDirectives(h('input'),[[vModelText,model,null,modifiers]])" 
          @update:modelValue="val => model=val" 
          @keydown.esc="model = memento"
        />