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?
<script>
import { ref } from 'vue'
export default {
setup() {
const bar = ref('init')
return { bar }
}
}
</script>
<template>
<input v-model='bar' />
</template>
>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" />