Creating Simple Component in Vuejs
Introduction
In this article, we will look at creating a very simple component in Vuejs. Let me pick the example from my previous post and create a component for showing the loading message.
Vuejs Component
There are two ways to create Vuejs component
- Single file component (.vue file) – this contains the component HTML template, Javascript and CSS in a single
.vue
file. Node based build tools are used to process these files. - Global components using
Vue.component
– in this we register the component definition as a JSON object using theVue.component
.
In our example here we will use the latter part because our component is simple and doesn’t warrant a lot of ceremonies.
Vuejs Component Definition
For our loading message component, the only value that needs to be passed is the message to be rendered and that will be accepted as an attribute of the component. Let us go ahead and define and register the component using the below code:
Vue.component('loading', { template: '<div class="alert alert-info">\ <i class="fa fa-spinner fa-spin"></i> {{message}} \ </div>', props: ["message"] });
In the above code:
- We define the component’s HTML using the
template
property. We can put in the HTML there or move the HTML in to a script template and refer that by id, something like:<script type="text/html" id="loading-template"> <div class="alert alert-info"> <i class="fa fa-spinner fa-spin"></i> {{message}} </div> </script> //and in component tempalte: '#loading-template'
- The attributes which it accepts are declared using,
props
property. Our component takes only 1 property which ismessage
Using the component
In the places where a loading message needs to be shown, add the following HTML:
<loading v-if="loadingDetail" :message="'Loading Detail...'"></loading>
Isn’t it very simple!!
Conclusion
You can find the complete code here. In my next post, I will show you how to create a Bootstrap pagination component. This will involve component state, event handling as well.
Published on Web Code Geeks with permission by Mohamed Sanaulla, partner at our WCG program. See the original article here: Creating Simple Component in Vuejs Opinions expressed by Web Code Geeks contributors are their own. |