[Vuejs]-Vue 2 – Create form with abstract v-model property

1πŸ‘

βœ…

In order to use data from a component in it’s slot, you need to use a scoped slot.

console.clear()

Vue.component("custom-form", {
  props: ["model", "url"],
  template: `
    <form :action="url">
      <slot :model="model"/>
    </form>
  `
})

new Vue({
  el: "#app",
  data: {
    model: {
      name: null,
      email: null,
      body: null,
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <custom-form :model="model" url="url/foo">
    <template slot-scope="props">
      <div class="form-group">
        <input id="name" name="name" v-model="props.model.name">
      </div>
    </template>
  </custom-form>
  <hr> {{model}}
</div>
πŸ‘€Bert

1πŸ‘

For that you need to use scoped-slot. See: https://v2.vuejs.org/v2/guide/components.html#Scoped-Slots

The idea is that in the child component you would declare somethings like:

<slot :model="model">...</slot>

And in the parent:

<custom-form 
  :model="{
            name: null,
            email: null,
            body: null,
          }" 
  url="url/foo">
 <div scop-slot="props" class="form-group">
  <input id="name" name="name" v-model="props.model.name">
 </div>
</custom-form>
πŸ‘€mathk

Leave a comment