Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue: v-model doesn't work with dynamic components

For example: <component v-model='foo' :is='boo' ...>.

foo's value stays the same during input.

I'm trying to solve the issue for quite a long time. I've checked lots of questions and threads but none of those helped me.

HTML doesn't work:

            <component
                :is="field.component"
                :key="key"
                :name="field.name"
                v-for="(field, key) in integration_data"
                v-model="field.value"
            >
            </component>

HTML works fine:

            <input
                :key="key"
                :name="field.name"
                v-for="(field, key) in integration_data"
                v-model="field.value"
            >

Vue controller:

export default {
init: function (init_data) {

    return new Vue({
        data: {
            integration_data: [
              {name: 'field_name0', component: 'input', value: ''},
              {name: 'field_name0', component: 'input', value: ''},
            ]
        },
    });
}
}
like image 213
BugDeveloper Avatar asked Dec 24 '22 16:12

BugDeveloper


1 Answers

You can't use input as a type of component and expect it to be a native input element. :is must name a component (which can contain an input, if you want).

Then you have to understand how v-model works on components:

So for a component to work with v-model, it should (these can be configured in 2.2.0+):

  • accept a value prop
  • emit an input event with the new value

Putting that all together, you can use v-model with :is.

new Vue({
  el: '#app',
  data: {
    integration_data: [{
      name: 'one',
      component: 'one',
      value: 'ok'
    }]
  },
  components: {
    one: {
      props: ['name', 'value'],
      template: '<div>{{name}} and <input v-model="proxyValue"><slot></slot></div>',
      computed: {
        proxyValue: {
          get() { return this.value; },
          set(newValue) { this.$emit('input', newValue); }
        }
      }
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <component 
    :is="field.component" 
    v-for="(field, key) in integration_data" 
    :key="key" 
    :name="field.name" 
    v-model="field.value"
  >
    <div>{{field.value}}</div>
  </component>
</div>
like image 127
Roy J Avatar answered Jan 07 '23 16:01

Roy J