Home  >  Q&A  >  body text

v-model not working with <component> in Vue 3?

<p>为什么在下面的示例中 v-model 没有绑定到我的输入? <code><component></code> 有限制吗?</p> <pre class="brush:php;toolbar:false;"><script setup> import { ref } from 'vue' const config = ref({ headers: [ { field: 'id', label: 'Id', component: { type: 'input' } }, { field: 'name', label: 'Name', component: { type: 'input' } }, // more configs for radio buttons and other custom components ], data: [ { id: 1, name: 'foo' }, { id: 2, name: 'bar' } ] }) </script> <template> <table> <tr> <td v-for="header in config.headers"> <b>{{ header.label }}</b> </td> </tr> <tr v-for="item in config.data"> <td v-for="header in config.headers"> <component :is="header.component.type" v-model="item[header.field]" /> </td> </tr> </table> {{ config.data }} </template></pre></p>
P粉806834059P粉806834059439 days ago431

reply all(1)I'll reply

  • P粉081360775

    P粉0813607752023-08-30 10:30:14

    Vue v-model Works great for native elements.

    But it obviously doesn't work with

    Your code generation

    <input modelvalue="foo">

    A very quick solution is to implement value binding directly.

    :value="item[header.field]" @input="item[header.field] = $event.target.value"

    But you will need to update the component accordingly to use value instead of modelValue.

    renew

    The workaround using v-model:value only works one way, the same as :value.

    <component :is="header.component.type" v-model:value="item[header.field]" />

    const { createApp, ref } = Vue
    
    const config = ref({
      headers: [
        { field: 'id', label: 'Id', component: { type: 'input' } }, 
        { field: 'name', label: 'Name', component: { type: 'input' }  },
        // more configs for radio buttons and other custom components
      ],
      data: [
        { id: 1, name: 'foo' },
        { id: 2, name: 'bar' }
      ]
    })
    
    const App = {
      setup() {
        return { config, test: 1 }  
      }
    }
    
    const app = createApp(App)
    app.mount('#app')
    #app { line-height: 1.75; }
    [v-cloak] { display: none; }
    <div id="app">
    <table>
        <tr>
          <td v-for="header in config.headers">
            <b>{{ header.label }}</b>
          </td>
        </tr>
        <tr v-for="item in config.data">
          <td v-for="header in config.headers">
            <component :is="header.component.type" :value="item[header.field]" @input="item[header.field] = $event.target.value" />
          </td>
        </tr>
      </table>
      {{ config.data }}
      <hr/>
      v-model test: <input v-model="test" />
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

    reply
    0
  • Cancelreply