Published on: 07 February, 2018

How to create a custom text box and button components in Vue.js?

Posted by andy | 390 views 0 likes 0 favourites 0 comments
Tumblr Digg Google Plus

In this tutorial, you will learn how to create your custom inputs components using Vue.js. You will also learn how the v-model works in Vue.js components and how to pass a button click event in custom button components.

What are components in Vue.js?

Components in Vue.js can be considered as extendible HTML templates which their templates can be reused. So when exactly you consider to use components? Well, You will use components when there are repeated same sections or areas in your application. So rather than have pretty much-repeated HTML codes again, why not just have a global component that can keep reuse and if you want to modify it, you just need to modify it in one place and the changes will apply to all places that use those components. Components support custom properties which enable you to alter or update the templates as needed.

In this example, we will create two basic components that will represent a text box and a button. User will be able to enter their name in the input text box and if the user click the button. It will alert a message box with their name. Before we start, let's define each input properties. For the text box component, it will have the following properties.

  • labelName
    When create an instance of this component, it will include a label name for this text box so an id of a text box is not required.
  • fieldID
    This property will include an input id attribute. This is optional, as we are going to use Vue.js binding model anyway.
  • cssClass
    This property will include a css class name. This is optional, by default we are going to use css class name input-field.
  • placeHolder
    This property will include a placeholder attribute. The place holder is an optional.
  • value
    This property will be used for model binding.

For the button component, it will have the following properties.

  • buttonName
    This will be the button name text.
  • fieldID
    This property will include a button id attribute. This is optional, as we are going to use Vue.js binding model anyway so an id of a button is not required.
  • cssClass
    This property will include a css class name. This is optional, by default we are going to use css class name input-button.
  • functionName
    If you want to add a click button event, you can include the function name in here.

The first thing we need is to include the Vue.js library. In this example, I am using the development library path.

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>

If you want to use the publish or released version, you can use the following Vue.js library url.

<script src="https://cdn.jsdelivr.net/npm/vue"></script>

This is the basic code to create your first component in Vue.js.

Vue.component('component-name', {
  // options
})

It is recommended for your component name to use all lowercase and hypen if it contains more than one word.

Here is the javascript code for our Vue.js iinput text box component.

Vue.component('input-text', {
    props: {
        labelName: {
            type: String,
            required: true
        },
        fieldId: {
            type: String,
            required: false
        },
        cssClass: {
            type: String,
            default: 'input-field'
        },
		placeHolder: {
			type: String,
			default: ''
		},
		value: {
			type: String,
			default: ''
		}
    },
    template:   `<div>
                    <label class='label-input' v-bind:for="fieldId">{{labelName}}</label>
                    <input v-bind:id="fieldId" v-bind:class="cssClass" v-bind:placeholder="placeHolder" v-bind:value="value" v-on:input="updateValue($event.target.value)"/>
                </div>`,
	methods: {
		updateValue: function(value){
			this.$emit('input', value)
		}
	}
})

In order for the v-model binding works in custom components in Vue.js, you have to include a function that will emit the input value. This can be done by attaching an input event which can be seen on the code.

v-on:input="updateValue($event.target.value)"

If you like to use the Vue.js shortcut, you can replace the word v-bind: to : and v-on: to @. I just include the whole words so you can know what they are. If we change the template to use the shortcut, it will end up like below.

<div>
	<label class='label-input' :for="fieldId">{{labelName}}</label>
	<input v-bind:id="fieldId" :class="cssClass" :placeholder="placeHolder" :value="value" @input="updateValue($event.target.value)"/>
</div>

This will be the javascript code for custom button Components in Vue.js.

Vue.component('input-button', {
    props: {
        buttonName: {
            type: String,
            required: true
        },
        fieldId: {
            type: String,
            required: false
        },
        cssClass: {
            type: String,
            default: 'input-button'
        },
		functionName:{
			type: String,
			required: false
		}
    },
    template: `<button  type='button' 
                        class='button-primary' 
                        v-bind:id="fieldId"
						v-on:click="callBackFunction">
                        {{buttonName}}
               </button>`,
	methods: {
		callBackFunction: function(){
			if(this.$parent && this.$parent[this.functionName]){
				this.$parent[this.functionName].call(this);
			}
		}
	}
})

If you see on above code, you will notice that I declare a property name functionName which will be used to store the function name. Inside this method, it will basically perform a check if an instance of Vue app has been created and the function name specified in the button Components exists in the app then perform a call or execution of this function.

to use the components we just need to include the components tag name like below.

<div id="sample-form">
	<input-text label-name='Enter your name: ' field-id='txtYourName' v-model='name' place-holder='Your name'></input-text>
	<input-button field-id='btnLogin' button-name="Login" function-name="alertName"></input-button>
</div>

One thing you have to remember is if you define a property name contains two words, which one of the word has a capital letter, it need to be separated with hypen. For example: labelName will become label-name. The second thing is when you are going to use a v-model on your text input, remember to declare a default property name in your Vue.js app. For example: our text box to input user name will have a v-model named name. See how we declare the variable name in the data section.

To run our Vue.js app, we just need to include the following javascript code.

new Vue({
	el: '#sample-form',
	data: {
		name: ''
	},
	methods: {
		alertName: function(){
			alert("How are you " + this.name + "?");
		}
	}
});

To tidy up our components, I have included the following css style.

<style>
.label-input{
	display:block;
	margin-bottom:10px;
}

.input-field{
	display:block;
	margin-bottom:10px;
}
</style>

Demo on how to create custom components in Vue.js

You can see the demo in here.

Feel free to post your comment below, if you have any question.

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.
Share your article with us and add your own google adsense account to earn extra money. Plus, you can promote a link back to your site.
Related Articles
Published on: 10 March, 2018
In this tutorial, you will learn how to create a custom form validation in Vue.js. I will create a simple validation using the help of JQuery library for the event attachment and DOM query. If you do not want to use JQuery, feel free to change it to native Javascript. The reason why I use JQuery library is to save time in the development phase. Let's get started with the concept.
Published on: 23 February, 2018
Once you have completed the development phase of your Vue.js app, you want to start deploying or publishing your Vue.js app. To deploy it is pretty simple, what you have to do is to deploy using the Node.js command prompt. Note: this only applies if you are using the CLI mode without using the Vue.js script tag directly
Published on: 23 February, 2018
To turn off the eslint feature in your Vue.js app is pretty simple. What you need to do is to go to the root folder and look for the config folder in your Vue.js project. There will be a file named index.js and look for the wording useEslint option.
Published on: 08 February, 2018
In this tutorial, you will learn on how to create custom directives in Vue.js. We will create two custom directives that will perform a check for an input that will accept numbers only and another custom directive that will accept whole numbers only. We will implement blur event on the input and if the user has entered wrong input. It will return 0 as default value.