Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Vue – using v-model on a <component> with :is

Is there a way in Vue to use v-model on a <component> whose tag is specified by :is='tag' (where tag obviously resolves to "input")?

This doesn’t work, i.e. the input does not contain the starting value "init".

<script>
import { ref } from 'vue'
export default {
  setup() {
    const tag = 'input'
    const bar = ref('init')
    return { tag, bar }
  }
}
</script>

<template>
  <component :is='tag' v-model='bar' />
</template>

This works, obviously, but can I do this with a dynamic tag name?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script>
import { ref } from 'vue'
export default {
  setup() {
    const bar = ref('init')
    return { bar }
  }
}
</script>

<template>
  <input v-model='bar' />
</template>

Demo

>Solution :

The v-model syntaxic sugar is treated differently whether you use it on a Vue component or a native html tag.

When used on a component, <MyInput v-model="msg" /> is equivalent of using
<MyInput :value="msg" @update:value="val => msg = val" />.

When used on an <input> tag, it’s translated like this:
<input :value="msg" @input="evt => msg = evt.target.value" />.

When using dynamic component <component :is="" />, Vue mostly assume it’s gonna be Vue components, so it will bind the event @update:value, which isn’t triggerred by the <input> element, and thus won’t update your binded variable.

Here, you should break down the v-model into the prop + event, like on the native input tag:

<component :is="tag" :value="bar" @input="evt => bar = evt.target.value" />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading