How to create a component for a html code in Vue?

2019-08-12 16:55发布

问题:

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.

回答1:

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.