user3204729
user3204729

Reputation: 317

Vuejs 2 How to update v-model by component

I would like to create a component for i-check but I cannot get the v-model data during form submission.

I can do it via normal input element.

Below is an example. Thanks

<!DOCTYPE html><html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <script src="https://unpkg.com/vue"></script>
  <title>JS Bin</title>
</head>
<body>
  <div id=wrap>
  <ichecker id="test" checked  v-model="formData.checkbox"></ichecker>
    <!--<input type=checkbox checked v-model="formData.checkbox" />-->
    <button v-on:click.prevent=submit()>Submit</button>
  </div>
</body>
</html>




Vue.component('ichecker', {
props: ['id', 'checked'],
model: {
    prop: 'checked',
    event: 'change'
},
template: "<input type='checkbox' :id='id' />",
mounted: () => {
  // var $el = jQuery(`#${this.id}`);
  // $el.iCheck({.....
}
});

new Vue ({
  el: '#wrap',
  data: {
    formData : {
      checkbox : ''
    }
  },
  methods: {
    submit: function() {
      document.body.appendChild(document.createTextNode(this.formData.checkbox?'true ':'false '));
      // form submission
    }
  }
});

https://jsbin.com/jugerigeto/edit?html,js,output

Upvotes: 0

Views: 1903

Answers (1)

FitzFish
FitzFish

Reputation: 8629

You are in a quite particular scenario where the <input> itself is the root element of your component. So you can't use v-model if you want to listen to the native event, cause it only exists on v-on. v-model is just a shorcut thought, and you can do it easily like this:

HTML:

<ichecker :checked="formData.checkbox"
    @change.native="formData.checkbox = $event.target.checked">
</ichecker>

JS:

Vue.component('ichecker', {
    prop: ['checked'],
    template: '<input type="checkbox" :checked="checked" />'
});

https://jsbin.com/suvonolita/edit?html,js,output

You may also want to do it without the native event, if the input is not your root node. Or you may really want v-model. The way to implement v-model on a custom component is described there: https://v2.vuejs.org/v2/guide/components.html#Customizing-Component-v-model

Upvotes: 1

Related Questions