VueJS – Quick Guide

VueJS – Quick Guide ”; Previous Next VueJS – Overview VueJS is an open source progressive JavaScript framework used to develop interactive web interfaces. It is one of the famous frameworks used to simplify web development. VueJS focusses on the view layer. It can be easily integrated into big projects for front-end development without any issues. The installation for VueJS is very easy to start with. Any developer can easily understand and build interactive web interfaces in a matter of time. VueJS is created by Evan You, an ex-employee from Google. The first version of VueJS was released in Feb 2014. It recently has clocked to 64,828 stars on GitHub, making it very popular. Features Following are the features available with VueJS. Virtual DOM VueJS makes the use of virtual DOM, which is also used by other frameworks such as React, Ember, etc. The changes are not made to the DOM, instead a replica of the DOM is created which is present in the form of JavaScript data structures. Whenever any changes are to be made, they are made to the JavaScript data structures and the latter is compared with the original data structure. The final changes are then updated to the real DOM, which the user will see changing. This is good in terms of optimization, it is less expensive and the changes can be made at a faster rate. Data Binding The data binding feature helps manipulate or assign values to HTML attributes, change the style, assign classes with the help of binding directive called v-bind available with VueJS. Components Components are one of the important features of VueJS that helps create custom elements, which can be reused in HTML. Event Handling v-on is the attribute added to the DOM elements to listen to the events in VueJS. Animation/Transition VueJS provides various ways to apply transition to HTML elements when they are added/updated or removed from the DOM. VueJS has a built-in transition component that needs to be wrapped around the element for transition effect. We can easily add third party animation libraries and also add more interactivity to the interface. Computed Properties This is one of the important features of VueJS. It helps to listen to the changes made to the UI elements and performs the necessary calculations. There is no need of additional coding for this. Templates VueJS provides HTML-based templates that bind the DOM with the Vue instance data. Vue compiles the templates into virtual DOM Render functions. We can make use of the template of the render functions and to do so we have to replace the template with the render function. Directives VueJS has built-in directives such as v-if, v-else, v-show, v-on, v-bind, and v-model, which are used to perform various actions on the frontend. Watchers Watchers are applied to data that changes. For example, form input elements. Here, we don’t have to add any additional events. Watcher takes care of handling any data changes making the code simple and fast. Routing Navigation between pages is performed with the help of vue-router. Lightweight VueJS script is very lightweight and the performance is also very fast. Vue-CLI VueJS can be installed at the command line using the vue-cli command line interface. It helps to build and compile the project easily using vue-cli. Comparison with Other Frameworks Now let us compare VueJS with other frameworks such as React, Angular, Ember, Knockout, and Polymer. VueJS v/s React Virtual DOM Virtual DOM is a virtual representation of the DOM tree. With virtual DOM, a JavaScript object is created which is the same as the real DOM. Any time a change needs to be made to the DOM, a new JavaScript object is created and the changes are made. Later, both the JavaScript objects are compared and the final changes are updated in the real DOM. VueJS and React both use virtual DOM, which makes it faster. Template v/s JSX VueJS uses html, js and css separately. It is very easy for a beginner to understand and adopt the VueJS style. The template based approach for VueJS is very easy. React uses jsx approach. Everything is JavaScript for ReactJS. HTML and CSS are all part of JavaScript. Installation Tools React uses create react app and VueJS uses vue-cli /CDN/npm. Both are very easy to use and the project is set up with all the basic requirements. React needs webpack for the build, whereas VueJS does not. We can start with VueJS coding anywhere in jsfiddle or codepen using the cdn library. Popularity React is popular than VueJS. The job opportunity with React is more than VueJS. There is a big name behind React i.e. Facebook which makes it more popular. Since, React uses the core concept of JavaScript, it uses the best practice of JavaScript. One who works with React will definitely be a very good with all the JavaScript concepts. VueJS is a developing framework. Presently, the job opportunities with VueJS are less in comparison to React. According to a survey, many people are adapting to VueJS, which can make it more popular in comparison to React and Angular. There is a good community working on the different features of VueJS. The vue-router is maintained by this community with regular updates. VueJS has taken the good parts from Angular and React and has built a powerful library. VueJS is much faster in comparison to React/Angular because of its lightweight library. VueJS v/s Angular Similarities VueJS has a lot of similarities with Angular. Directives such as v-if, v-for are almost similar to ngIf, ngFor of Angular. They both have a command line interface for project installation and to build it. VueJS uses Vue-cli and Angular uses angular-cli. Both offer two-way data binding, server side rendering, etc. Complexity Vuejs is very easy to learn and start with. As discussed earlier, a beginner can take the CDN library of VueJS and get started in codepen and jsfiddle. For Angular, we need to go through a series

VueJS – Reactive Interface

VueJS – Reactive Interface ”; Previous Next VueJS provides options to add reactivity to properties, which are added dynamically. Consider that we have already created vue instance and need to add the watch property. It can be done as follows − Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “app”> <p style = “font-size:25px;”>Counter: {{ counter }}</p> <button @click = “counter++” style = “font-size:25px;”>Click Me</button> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#app”, data: { counter: 1 } }); vm.$watch(”counter”, function(nval, oval) { alert(”Counter is incremented :” + oval + ” to ” + nval + ”!”); }); setTimeout( function(){ vm.counter = 20; },2000 ); </script> </body> </html> There is a property counter defined as 1 in data object. The counter is incremented when we click the button. Vue instance is already created. To add watch to it, we need to do it as follows − vm.$watch(”counter”, function(nval, oval) { alert(”Counter is incremented :” + oval + ” to ” + nval + ”!”); }); We need to use $watch to add watch outside the vue instance. There is an alert added, which shows the value change for the counter property. There is also a timer function added, i.e. setTimeout, which sets the counter value to 20. setTimeout( function(){ vm.counter = 20; },2000 ); Whenever the counter is changed, the alert from the watch method will get fired as shown in the following screenshot. VueJS cannot detect property addition and deletion. The best way is to always declare the properties, which needs to be reactive upfront in the Vue instance. In case we need to add properties at run time, we can make use of Vue global, Vue.set, and Vue.delete methods. Vue.set This method helps to set a property on an object. It is used to get around the limitation that Vue cannot detect property additions. Syntax Vue.set( target, key, value ) Where, target: Can be an object or an array key : Can be a string or number value: Can be any type Let’s take a look at an example. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “app”> <p style = “font-size:25px;”>Counter: {{ products.id }}</p> <button @click = “products.id++” style = “font-size:25px;”>Click Me</button> </div> <script type = “text/javascript”> var myproduct = {“id”:1, name:”book”, “price”:”20.00″}; var vm = new Vue({ el: ”#app”, data: { counter: 1, products: myproduct } }); vm.products.qty = “1”; console.log(vm); vm.$watch(”counter”, function(nval, oval) { alert(”Counter is incremented :” + oval + ” to ” + nval + ”!”); }); </script> </body> </html> In the above example, there is a variable myproduct created at the start using the following piece of code. var myproduct = {“id”:1, name:”book”, “price”:”20.00″}; It is given to the data object in Vue instance as follows − var vm = new Vue({ el: ”#app”, data: { counter: 1, products: myproduct } }); Consider, we want to add one more property to the myproduct array, after the Vue instance is created. It can be done as follows − vm.products.qty = “1”; Let’s see the output in the console. As seen above, in products the quantity is added. The get/set methods, which basically adds reactivity is available for the id, name, and price, and not available for qty. We cannot achieve the reactivity by just adding vue object. VueJS mostly wants all its properties to be created at the start. However, in case we need to add it later, we can use Vue.set. For this, we need to set it using vue global, i.e. Vue.set. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “app”> <p style = “font-size:25px;”>Counter: {{ products.id }}</p> <button @click = “products.id++” style = “font-size:25px;”>Click Me</button> </div> <script type = “text/javascript”> var myproduct = {“id”:1, name:”book”, “price”:”20.00″}; var vm = new Vue({ el: ”#app”, data: { counter: 1, products: myproduct } }); Vue.set(myproduct, ”qty”, 1); console.log(vm); vm.$watch(”counter”, function(nval, oval) { alert(”Counter is incremented :” + oval + ” to ” + nval + ”!”); }); </script> </body> </html> We have used Vue.set to add the qty to the array using the following piece of code. Vue.set(myproduct, ”qty”, 1); We have consoled the vue object and following is the output. Now, we can see the get/set for qty added using Vue.set. Vue.delete This function is used to delete the property dynamically. Example Vue.delete( target, key ) Where, target: Can be an object or an array key: Can be a string or a number To delete any property, we can use Vue.delete as in the following code. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “app”> <p style = “font-size:25px;”>Counter: {{ products.id }}</p> <button @click = “products.id++” style = “font-size:25px;”>Click Me</button> </div> <script type = “text/javascript”> var myproduct = {“id”:1, name:”book”, “price”:”20.00″}; var vm = new Vue({ el: ”#app”, data: { counter: 1, products: myproduct } }); Vue.delete(myproduct, ”price”); console.log(vm); vm.$watch(”counter”, function(nval, oval) { alert(”Counter is incremented :” + oval + ” to ” + nval + ”!”); }); </script> </body> </html> In the above example, we have used Vue.delete to delete the price from the array using the following piece of code. Vue.delete(myproduct, ”price”); Following is the output, we see in the console. After deletion, we can see only the id and name as the price is deleted. We can also notice that the get/set methods are deleted. Print Page Previous Next Advertisements ”;

VueJS – Computed Properties

VueJS – Computed Properties ”; Previous Next We have already seen methods for Vue instance and for components. Computed properties are like methods but with some difference in comparison to methods, which we will discuss in this chapter. At the end of this chapter, we will be able to make a decision on when to use methods and when to use computed properties. Let’s understand computed properties using an example. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “computed_props”> FirstName : <input type = “text” v-model = “firstname” /> <br/><br/> LastName : <input type = “text” v-model = “lastname”/> <br/><br/> <h1>My name is {{firstname}} {{lastname}}</h1> <h1>Using computed method : {{getfullname}}</h1> </div> <script type = “text/javascript” src = “js/vue_computedprops.js”></script> </body> </html> vue_computeprops.js var vm = new Vue({ el: ”#computed_props”, data: { firstname :””, lastname :””, birthyear : “” }, computed :{ getfullname : function(){ return this.firstname +” “+ this.lastname; } } }) Here, we have created .html file with firstname and lastname. Firstname and Lastname is a textbox which are bound using properties firstname and lastname. We are calling the computed method getfullname, which returns the firstname and the lastname entered. computed :{ getfullname : function(){ return this.firstname +” “+ this.lastname; } } When we type in the textbox the same is returned by the function, when the properties firstname or lastname is changed. Thus, with the help of computed we don’t have to do anything specific, such as remembering to call a function. With computed it gets called by itself, as the properties used inside changes, i.e. firstname and lastname. The same is displayed in the following browser. Type in the textbox and the same will get updated using the computed function. Now, let’s try to understand the difference between a method and a computed property. Both are objects. There are functions defined inside, which returns a value. In case of method, we call it as a function, and for computed as a property. Using the following example, let us understand the difference between method and computed property. <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “computed_props”> <h1 style = “background-color:gray;”>Random No from computed property: {{getrandomno}}</h1> <h1>Random No from method: {{getrandomno1()}}</h1> <h1>Random No from method : {{getrandomno1()}}</h1> <h1 style = “background-color:gray;”>Random No from computed property: {{getrandomno}}</h1> <h1 style = “background-color:gray;”>Random No from computed property: {{getrandomno}}</h1> <h1 style = “background-color:gray;”>Random No from computed property: {{getrandomno}}</h1> <h1>Random No from method: {{getrandomno1()}}</h1> <h1>Random No from method: {{getrandomno1()}}</h1> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#computed_props”, data: { name : “helloworld” }, methods: { getrandomno1 : function() { return Math.random(); } }, computed :{ getrandomno : function(){ return Math.random(); } } }); </script> </body> </html> In the above code, we have created a method called getrandomno1 and a computed property with a function getrandomno. Both are giving back random numbers using Math.random(). It is displayed in the browser as shown below. The method and computed property are called many times to show the difference. If we look at the values above, we will see that the random numbers returned from the computed property remains the same irrespective of the number of times it is called. This means everytime it is called, the last value is updated for all. Whereas for a method, it’s a function, hence, everytime it is called it returns a different value. Get/Set in Computed Properties In this section, we will learn about get/set functions in computed properties using an example. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “computed_props”> <input type = “text” v-model = “fullname” /> <h1>{{firstName}}</h1> <h1>{{lastName}}</h1> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#computed_props”, data: { firstName : “Terry”, lastName : “Ben” }, methods: { }, computed :{ fullname : { get : function() { return this.firstName+” “+this.lastName; } } } }); </script> </body> </html> We have defined one input box which is bound to fullname, which is a computed property. It returns a function called get, which gives the fullname, i.e. the first name and the lastname. Also, we have displayed the firstname and lastname as − <h1>{{firstName}}</h1> <h1>{{lastName}}</h1> Let’s check the same in the browser. Now, if we change the name in the textbox, we will see the same is not reflected in the name displayed in the following screenshot. Let’s add the setter function in the fullname computed property. <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “computed_props”> <input type = “text” v-model = “fullname” /> <h1>{{firstName}}</h1> <h1>{{lastName}}</h1> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#computed_props”, data: { firstName : “Terry”, lastName : “Ben” }, methods: { }, computed :{ fullname : { get : function() { return this.firstName+” “+this.lastName; }, set : function(name) { var fname = name.split(” “); this.firstName = fname[0]; this.lastName = fname[1] } } } }); </script> </body> </html> We have added the set function in the fullname computed property. computed :{ fullname : { get : function() { return this.firstName+” “+this.lastName; }, set : function(name) { var fname = name.split(” “); this.firstName = fname[0]; this.lastName = fname[1] } } } It has the name as the parameter, which is nothing but the fullname in the textbox. Later, it is split on space and the firstname and the lastname is updated. Now, when we run the code and edit the textbox, the same thing will be displayed in the browser. The firstname and the lastname will be updated because of the set function. The get function returns the firstname and lastname, while the set function updates it, if anything is edited. Now, whatever is typed in the textbox matches with what is displayed as seen in the above screenshot. Print Page Previous Next Advertisements

VueJS – Environment Setup

VueJS – Environment Setup ”; Previous Next There are many ways to install VueJS. Some of the ways on how to carry out the installation are discussed ahead. Using the <script> tag directly in HTML file <html> <head> <script type = “text/javascript” src = “vue.min.js”></script> </head> <body></body> </html> Go to the home site https://vuejs.org/v2/guide/installation.html of VueJS and download the vue.js as per need. There are two versions for use – production version and development version. The development version is not minimized, whereas the production version is minimized as shown in the following screenshot. Development version will help with the warnings and debug mode during the development of the project. Using CDN We can also start using VueJS file from the CDN library. The link https://unpkg.com/vue will give the latest version of VueJS. VueJS is also available on jsDelivr (https://cdn.jsdelivr.net/npm/vue/dist/vue.js) and cdnjs (https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js). We can host the files at our end, if required and get started with VueJS development. Using NPM For large scale applications with VueJS, it is recommended to install using the npm package. It comes with Browserify and Webpack along with other necessary tools, which help with the development. Following is the command to install using npm. npm install vue Using CLI Command Line VueJS also provides CLI to install the vue and get started with the server activation. To install using CLI, we need to have CLI installed which is done using the following command. npm install –global vue-cli Once done, it shows the CLI version for VueJS. It takes a few minutes for the installation. + [email protected] added 965 packages in 355.414s Following is the command to create the project using Webpack. vue init webpack myproject To get started, use the following command. cd myproject npm install npm run dev Once we execute npm run dev, it starts the server and provides the url for display to be seen in the browser which is as shown in the following screenshot. The project structure using CLI looks like the following. Print Page Previous Next Advertisements ”;

VueJS – Events

VueJS – Events ”; Previous Next v-on is the attribute added to the DOM elements to listen to the events in VueJS. Click Event Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “databinding”> <button v-on:click = “displaynumbers”>Click ME</button> <h2> Add Number 100 + 200 = {{total}}</h2> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { num1: 100, num2 : 200, total : ”” }, methods : { displaynumbers : function(event) { console.log(event); return this.total = this.num1+ this.num2; } }, }); </script> </body> </html> Output The following code is used to assign a click event for the DOM element. <button v-on:click = “displaynumbers”>Click ME</button> There is a shorthand for v-on, which means we can also call the event as follows − <button @click = “displaynumbers”>Click ME</button> On the click of the button, it will call the method ‘displaynumbers’, which takes in the event and we have consoled the same in the browser as shown above. We will now check one more event mouseover mouseout. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “databinding”> <div v-bind:style = “styleobj” v-on:mouseover = “changebgcolor” v-on:mouseout = “originalcolor”></div> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { num1: 100, num2 : 200, total : ””, styleobj : { width:”100px”, height:”100px”, backgroundColor:”red” } }, methods : { changebgcolor : function() { this.styleobj.backgroundColor = “green”; }, originalcolor : function() { this.styleobj.backgroundColor = “red”; } }, }); </script> </body> </html> In the above example, we have created a div with width and height as 100px. It has been given a background color red. On mouseover, we are changing the color to green, and on mouseout we are changing the color back to red. Hence, during mouseover, a method is called changebgcolor and once we move the mouse out of the div, a method is called originalcolor. This is done as follows − <div v-bind:style = “styleobj” v-on:mouseover = “changebgcolor” v-on:mouseout = “originalcolor”></div> Two events – mouseover and mouseout – is assigned to the div as shown above. We have created a styleobj variable and given the required style to be assigned to the div. The same variable is binded to the div using v-bind:style = ”styleobj” In changebgcolor, we are changing the color to green using the following code. changebgcolor : function() { this.styleobj.backgroundColor = “green”; } Using the stylobj variable, we are changing the color to green. Similarly, the following code is used to change it back to the original color. originalcolor : function() { this.styleobj.backgroundColor = “red”; } This is what we see in the browser. When we mouseover, the color will change to green as shown in the following screenshot. Event Modifiers Vue has event modifiers available on v-on attribute. Following are the modifiers available − .once Allows the event to execute only once. Syntax <button v-on:click.once = “buttonclicked”>Click Once</button> We need to add dot operator while calling the modifiers as shown in the syntax above. Let us use it in an example and understand the working of the once modifier. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “databinding”> <button v-on:click.once = “buttonclickedonce” v-bind:style = “styleobj”>Click Once</button> Output:{{clicknum}} <br/><br/> <button v-on:click = “buttonclicked” v-bind:style = “styleobj”>Click Me</button> Output:{{clicknum1}} </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { clicknum : 0, clicknum1 :0, styleobj: { backgroundColor: ”#2196F3!important”, cursor: ”pointer”, padding: ”8px 16px”, verticalAlign: ”middle”, } }, methods : { buttonclickedonce : function() { this.clicknum++; }, buttonclicked : function() { this.clicknum1++; } } }); </script> </body> </html> Output In the above example, we have created two butttons. The button with Click Once label has added the once modifier and the other button is without any modifier. This is the way the buttons are defined. <button v-on:click.once = “buttonclickedonce” v-bind:style = “styleobj”>Click Once</button> <button v-on:click = “buttonclicked” v-bind:style = “styleobj”>Click Me</button> The first button calls the method “buttonclickedonce” and the second button calls the method “buttonclicked”. buttonclickedonce : function() { this.clicknum++; }, buttonclicked : function() { this.clicknum1++; } There are two variables defined in the clicknum and clicknum1. Both are incremented when the button is clicked. Both the variables are initialized to 0 and the display is seen in the output above. On the click of the first button, the variable clicknum increments by 1. On the second click, the number is not incremented as the modifier prevents it from executing or performing any action item assigned on the click of the button. On the click of the second button, the same action is carried out, i.e. the variable is incremented. On every click, the value is incremented and displayed. Following is the output we get in the browser. .prevent Syntax <a href = “http://www.google.com” v-on:click.prevent = “clickme”>Click Me</a> Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “databinding”> <a href = “http://www.google.com” v-on:click = “clickme” target = “_blank” v-bind:style = “styleobj”>Click Me</a> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { clicknum : 0, clicknum1 :0, styleobj: { color: ”#4CAF50”, marginLeft: ”20px”, fontSize: ”30px” } }, methods : { clickme : function() { alert(“Anchor tag is clicked”); } } }); </script> </body> </html> Output If we click the clickme link, it will send an alert as “Anchor tag is clicked” and it will open the link https://www.google.com in a new tab as shown in the following screenshots. Now this works as a normal way, i.e. the link opens up as we want. In case we don’t want the link to open up, we need to add a modifier ‘prevent’ to the event as shown in the following code. <a href = “http://www.google.com” v-on:click.prevent = “clickme” target = “_blank” v-bind:style = “styleobj”>Click Me</a> Once added, if we click on the button, it will send an alert message and will

VueJS – Components

VueJS – Components ”; Previous Next Vue Components are one of the important features of VueJS that creates custom elements, which can be reused in HTML. Let’s work with an example and create a component, that will give a better understanding on how components work with VueJS. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “component_test”> <testcomponent></testcomponent> </div> <div id = “component_test1”> <testcomponent></testcomponent> </div> <script type = “text/javascript” src = “js/vue_component.js”></script> </body> </html> vue_component.js Vue.component(”testcomponent”,{ template : ”<div><h1>This is coming from component</h1></div>” }); var vm = new Vue({ el: ”#component_test” }); var vm1 = new Vue({ el: ”#component_test1” }); In the .html file, we have created two div with id component_test and component_test1. In the .js files shown above, two Vue instances are created with the div ids. We have created a common component to be used with both the view instances. To create a component, following is the syntax. Vue.component(”nameofthecomponent”,{ // options}); Once a component is created, the name of the component becomes the custom element and the same can be used in the Vue instance element created, i.e. inside the div with ids component_test and component_test1. In the .js file, we have used a test component as the name of the component and the same name is used as the custom element inside the divs. Example <div id = “component_test”> <testcomponent></testcomponent> </div> <div id = “component_test1″> <testcomponent></testcomponent> </div> In the component created in the .js file, we have added a template to which we have assigned a HTML code. This is a way of registering a global component, which can be made a part of any vue instance as shown in the following script. Vue.component(”testcomponent”,{ template : ”<div><h1>This is coming from component</h1></div>” }); On execution, the same will be reflected in the browser. The components are given the custom element tag, i.e. <testcomponent></testcomponent>. However, when we inspect the same in the browser, we will not notice the custom tag in plain HTML present in the template as shown in the following screenshot. We have also directly made the components a part of vue instance as shown in the following script. var vm = new Vue({ el: ”#component_test”, components:{ ”testcomponent”: { template : ”<div><h1>This is coming from component</h1></div>” } } }); This is called local registration and the components will be a part of only the vue instance created. So far, we have seen the basic component with the basic options. Now, let’s add some more options such as data and methods to it. Just as Vue instance has data and methods, component also shares the same. Hence, we will extend the code, which we have already seen with data and methods. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “component_test”> <testcomponent></testcomponent> </div> <div id = “component_test1”> <testcomponent></testcomponent> </div> <script type = “text/javascript” src = “js/vue_component.js”></script> </body> </html> vue_component.js Vue.component(”testcomponent”,{ template : ”<div v-on:mouseover = “changename()” v-on:mouseout = “originalname();”><h1>Custom Component created by <span id = “name”>{{name}}</span></h1></div>”, data: function() { return { name : “Ria” } }, methods:{ changename : function() { this.name = “Ben”; }, originalname: function() { this.name = “Ria”; } } }); var vm = new Vue({ el: ”#component_test” }); var vm1 = new Vue({ el: ”#component_test1” }); In the .js file above, we have added data that is a function, which returns an object. The object has a name property, which is assigned the value ‘Ria’. This is used in the following template. template : ”<div v-on:mouseover = “changename()” v-on:mouseout = “originalname();”><h1>Custom Component created by <span id = “name”>{{name}}</span></h1></div>”, In spite of having data as a function in components, we can use its properties the same way as we use with direct Vue instance. Also, there are two methods added, changename and originalname. In changename, we are changing the name property, and in originalname we are resetting it back to the original name. We have also added two events on the div, mouseover and mouseout. The details of the events will be discussed in the Events chapter. So for now, mouseover calls changename method and mouseout calls originalname method. The display of the same is shown in the following browser. As seen in the above browser, it displays the name assigned in the data property, which is the same name. We have also assigned a mouseover event on the div and also a mouseout. Let’s see what happens when we mouseover and mouseout. On mouseover, we see the name of the first component is changed to Ben, however, the second one remains as it is. This is because the data component is a function and it returns an object. Thus, when it is changed in one place, the same is not overwritten in other cases. Dynamic Components Dynamic components are created using the keyword <component></component> and it is bound using a property as shown in the following example. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “databinding”> <component v-bind:is = “view”></component> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { view: ”component1” }, components: { ”component1”: { template: ”<div><span style = “font-size:25;color:red;”>Dynamic Component</span></div>” } } }); </script> </body> </html> Output Dynamic component is created using the following syntax. <component v-bind:is = “view”></component> It has v-bind:is = ”view”, and a value view is assigned to it. View is defined in the Vue instance as follows. var vm = new Vue({ el: ”#databinding”, data: { view: ”component1” }, components: { ”component1”: { template: ”<div><span style = “font-size:25;color:red;”>Dynamic Component</span></div>” } } }); When executed, the template Dynamic Component is displayed in the browser. Print Page Previous Next Advertisements ”;

VueJS – Render Function

VueJS – Render Function ”; Previous Next We have seen components and the usage of it. For example, we have a content that needs to be reused across the project. We can convert the same as a component and use it. Let’s take a look at an example of a simple component and see what the render function has to do within it. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “component_test”> <testcomponent></testcomponent> </div> <script type = “text/javascript”> Vue.component(”testcomponent”,{ template : ”<h1>Hello World</h1>”, data: function() { }, methods:{ } }); var vm = new Vue({ el: ”#component_test” }); </script> </body> </html> Consider the above example of a simple component that prints Hello World as shown in the following screenshot. Now, if we want to reuse the component, we can do so by just printing it again. For example, <div id = “component_test”> <testcomponent></testcomponent> <testcomponent></testcomponent> <testcomponent></testcomponent> <testcomponent></testcomponent> </div> And the output will be the following. However, now we need some changes to the component. We don’t want the same text to be printed. How can we change it? In case, we type something inside the component, will it be take into consideration? Let us consider the following example and see what happens. <div id = “component_test”> <testcomponent>Hello Jai</testcomponent> <testcomponent>Hello Roy</testcomponent> <testcomponent>Hello Ria</testcomponent> <testcomponent>Hello Ben</testcomponent> </div> The output remains the same as we had seen earlier. It does not change the text as we want. Component does provide something called as slots. Let’s make use of it and see if we get the desired results. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “component_test”> <testcomponent>Hello Jai</testcomponent> <testcomponent>Hello Roy</testcomponent> <testcomponent>Hello Ria</testcomponent> <testcomponent>Hello Ben</testcomponent> </div> <script type = “text/javascript”> Vue.component(”testcomponent”,{ template : ”<h1><slot></slot></h1>”, data: function() { }, methods:{ } }); var vm = new Vue({ el: ”#component_test” }); </script> </body> </html> As seen in the above code, in the template we have added slot, hence now it takes the value to send inside the component as shown in the following screenshot. Now, let us consider we want to change the color and size. For example, currently we are using h1 tag and we want to change the HTML tag to p tag or div tag for the same component. How can we have the flexibility to carry out so many changes? We can do so with the help of the render function. Render function helps make the component dynamic and use the way it is required by keeping it common and helping pass arguments using the same component. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “component_test”> <testcomponent :elementtype = “”div,red,25,div1””>Hello Jai</testcomponent> <testcomponent :elementtype = “”h3,green,25,h3tag””>Hello Roy</testcomponent> <testcomponent :elementtype = “”p,blue,25,ptag””>Hello Ria</testcomponent> <testcomponent :elementtype = “”div,green,25,divtag””>Hello Ben</testcomponent> </div> <script type = “text/javascript”> Vue.component(”testcomponent”,{ render :function(createElement){ var a = this.elementtype.split(“,”); return createElement(a[0],{ attrs:{ id:a[3], style:”color:”+a[1]+”;font-size:”+a[2]+”;” } }, this.$slots.default ) }, props:{ elementtype:{ attributes:String, required:true } } }); var vm = new Vue({ el: ”#component_test” }); </script> </body> </html> In the above code, we have changed the component and added the render function with props property using the following piece of code. Vue.component(”testcomponent”,{ render :function(createElement){ var a = this.elementtype.split(“,”); return createElement(a[0],{ attrs:{ id:a[3], style:”color:”+a[1]+”;font-size:”+a[2]+”;” } }, this.$slots.default ) }, props:{ elementtype:{ attributes:String, required:true } } }); The props look like the following. props:{ elementtype:{ attributes:String, required:true } } We have defined a property called elementtype, which takes attributes field of type string. Another required field, which mentions that the field is mandatory. In the render function, we have used the elementtype property as seen in the following piece of code. render :function(createElement){ var a = this.elementtype.split(“,”); return createElement(a[0],{ attrs:{ id:a[3], style:”color:”+a[1]+”;font-size:”+a[2]+”;” } }, this.$slots.default ) } Render function takes createElement as the argument and returns the same. CreateElement creates the DOM element the same way as in JavaScript. We have also split the elementtype on comma, using the values in the attrs field. CreateElement is taking the first param as the elementtag to be created. It is passed to the component using the following piece of code. <testcomponent :elementtype = “”div,red,25,div1””>Hello Jai</testcomponent> The component needs to take the props field as shown above. It starts with : and the name of the props. Here, we are passing the element tag, color, fontsize, and the id of the element. In render function, in createElement, we are splitting on comma, so the first element is the elementtag, which is given to the createElemet as shown in the following piece of code. return createElement( a[0],{ attrs:{ id:a[3], style:”color:”+a[1]+”;font-size:”+a[2]+”;” } }, this.$slots.default ) a[0] is the html element tag. The next parameter is the attributes for the element tag. They are defined in the attr field in the following piece of code. attrs:{ id:a[3], style:”color:”+a[1]+”;font-size:”+a[2]+”;” } We have defined two attributes for the element tag – id and style. To id, we are passing a[3], which is the value we have after splitting on comma. Using style, we have defined color and fontsize. Last is the slot, that is the message we have given in the componentin the following piece of code. <testcomponent :elementtype = “”div,red,25,div1””>Hello Jai</testcomponent> We have defined the text to be printed in the createElement using the following piece of code. this.$slots.default It takes the default assigned in the component field. Following is the output we get in the browser. The elements also show the structure. These are the components we have defined − <div id = “component_test”> <testcomponent :elementtype = “”div,red,25,div1””>Hello Jai</testcomponent> <testcomponent :elementtype = “”h3,green,25,h3tag””>Hello Roy</testcomponent> <testcomponent :elementtype = “”p,blue,25,ptag””>Hello Ria</testcomponent> <testcomponent :elementtype = “”div,green,25,divtag””>Hello Ben</testcomponent> </div> Print Page Previous Next Advertisements ”;