1

So I have this code:

<div class="input-field col s12 m6 l6">
   <input id="txtboxid" type="text" v-model="full_name">
   <label for="txtboxid">Middle Name *</label>
</div>

And I have lots of those with different ID's and model's and my html file looks big. Is there a way to make it shorter in vuejs? Like just a single line and it will have those? Any help would be much appreciated.

4
  • Just my 2 cents, put your IDs and names into an object or an array, loop them by using v-for. IDs could be set by using v-bind. Commented Feb 10, 2017 at 4:16
  • @choasia ha! I like that idea. Commented Feb 10, 2017 at 4:17
  • 1
    See fiddle with Vue . Enjoy! Commented Feb 10, 2017 at 4:18
  • 1
    Dude @AbdennourTOUMI I need to use Vue for this for some purposes. Thanks for the recommendation btw Commented Feb 10, 2017 at 4:20

1 Answer 1

4

As you have pointed out in the question, itself, you can create re-usable components in Vue.js, for using the same HTML template again and again. You can create a simple vue component from your code as following:

Vue.component('child', {
  template: '\
   <div class="input-field col s12 m6 l6"> \
   <input :id="id" type="text" v-model="value"> \
   <label for="txtboxid">Middle Name *</label> \
</div> \
  ',
  props: [
      "id", "value"],
  watch: {
    value: function(newVal){
       this.$emit('input', newVal)
    }
  }
})

and it can be used in your HTML just by using single line:

<child v-model="full_name" id="24"></child>

Please check working fiddler here.

In the above code I am using watch, you can also use event handler on change @change to get the full_name updated in the parent, demo here.

Some Explanation:

I am using v-model here. <input v-model="something"> here, which is essentially syntactic sugar for:

<input v-bind:value="something" v-on:input="something = $event.target.value">

You can use this to create components and send your varaible in v-model and accept it in the component as props.

Sign up to request clarification or add additional context in comments.

3 Comments

I think a specific event handler (such as v-on:input) would be better than watch. Nice answer though
@Phil Thanks for your recommendation, I have changed the code, please have a look here.
Did you see the warning message in the console whenever you type something in the textbox? @Saurabh

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.