VueJS – Mixins ”; Previous Next Mixins are basically to be used with components. They share reusable code among components. When a component uses mixin, all options of mixin become a part of the component options. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “databinding”></div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { }, methods : { }, }); var myMixin = { created: function () { this.startmixin() }, methods: { startmixin: function () { alert(“Welcome to mixin example”); } } }; var Component = Vue.extend({ mixins: [myMixin] }) var component = new Component(); </script> </body> </html> Output When a mixin and a component contain overlapping options, they are merged as shown in the following example. <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “databinding”></div> <script type = “text/javascript”> var mixin = { created: function () { console.log(”mixin called”) } } new Vue({ mixins: [mixin], created: function () { console.log(”component called”) } }); </script> </body> </html> Now the mixin and the vue instance has the same method created. This is the output we see in the console. As seen, the option of the vue and the mixin will be merged. If we happen to have the same function name in methods, then the main vue instance will take priority. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “databinding”></div> <script type = “text/javascript”> var mixin = { methods: { hellworld: function () { console.log(”In HelloWorld”); }, samemethod: function () { console.log(”Mixin:Same Method”); } } }; var vm = new Vue({ mixins: [mixin], methods: { start: function () { console.log(”start method”); }, samemethod: function () { console.log(”Main: same method”); } } }); vm.hellworld(); vm.start(); vm.samemethod(); </script> </body> </html> We will see mixin has a method property in which helloworld and samemethod functions are defined. Similarly, vue instance has a methods property in which again two methods are defined start and samemethod. Each of the following methods are called. vm.hellworld(); // In HelloWorld vm.start(); // start method vm.samemethod(); // Main: same method As seen above, we have called helloworld, start, and samemethod function. samemethod is also present in mixin, however, priority will be given to the main instance, as seen in the following console. Print Page Previous Next Advertisements ”;
Category: vuejs
VueJS – Useful Resources
VueJS – Useful Resources ”; Previous Next The following resources contain additional information on VueJS. Please use them to get more in-depth knowledge on this. Useful Video Courses Full Stack Development With Vue JS 2 And Spring Boot 54 Lectures 3.5 hours Senol Atac More Detail Node js for Course for beginners + Game project 27 Lectures 2.5 hours Laurence Svekis More Detail Advanced Theoretical JavaScript: Learn Advanced JS Concepts 25 Lectures 2 hours Mehul Mohan More Detail ReactJS Course : Learn React JS From Scratch Best Seller 61 Lectures 4.5 hours Skillbakery More Detail JavaScript Deep Dive: Explore JS (For Beginners-to-Advanced) 129 Lectures 5.5 hours TELCOMA Global More Detail React JS and .NET Core Web API Full Stack Master Course 21 Lectures 3.5 hours Vinay Kumar More Detail Print Page Previous Next Advertisements ”;
VueJS – Discussion
Discuss VueJS ”; Previous Next VueJS is a progressive JavaScript framework used to develop interactive web interfaces. Focus is more on the view part, which is the front end. It is very easy to integrate with other projects and libraries. The installation of VueJS is fairly simple, and beginners can easily understand and start building their own user interfaces. The content is divided into various chapters that contain related topics with simple and useful examples. Print Page Previous Next Advertisements ”;
VueJS – Instances
VueJS – Instances ”; Previous Next To start with VueJS, we need to create the instance of Vue, which is called the root Vue Instance. Syntax var app = new Vue({ // options }) Let us look at an example to understand what needs to be part of the Vue constructor. <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “vue_det”> <h1>Firstname : {{firstname}}</h1> <h1>Lastname : {{lastname}}</h1> <h1>{{mydetails()}}</h1> </div> <script type = “text/javascript” src = “js/vue_instance.js”></script> </body> </html> vue_instance.js var vm = new Vue({ el: ”#vue_det”, data: { firstname : “Ria”, lastname : “Singh”, address : “Mumbai” }, methods: { mydetails : function() { return “I am “+this.firstname +” “+ this.lastname; } } }) For Vue, there is a parameter called el. It takes the id of the DOM element. In the above example, we have the id #vue_det. It is the id of the div element, which is present in .html. <div id = “vue_det”></div> Now, whatever we are going to do will affect the div element and nothing outside it. Next, we have defined the data object. It has value firstname, lastname, and address. The same is assigned inside the div. For example, <div id = “vue_det”> <h1>Firstname : {{firstname}}</h1> <h1>Lastname : {{lastname}}</h1> </div> The Firstname : {{firstname}} value will be replaced inside the interpolation, i.e. {{}} with the value assigned in the data object, i.e. Ria. The same goes for last name. Next, we have methods where we have defined a function mydetails and a returning value. It is assigned inside the div as <h1>{{mydetails()}}</h1> Hence, inside {{} } the function mydetails is called. The value returned in the Vue instance will be printed inside {{}}. Check the output for reference. Output Now, we need to pass options to the Vue constructor which is mainly data, template, element to mount on, methods, callbacks, etc. Let us take a look at the options to be passed to the Vue. #data − This type of data can be an object or a function. Vue converts its properties to getters/setters to make it reactive. Let’s take a look at how the data is passed in the options. Example <html> <head> <title>VueJs Introduction</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <script type = “text/javascript”> var _obj = { fname: “Raj”, lname: “Singh”} // direct instance creation var vm = new Vue({ data: _obj }); console.log(vm.fname); console.log(vm.$data); console.log(vm.$data.fname); </script> </body> </html> Output console.log(vm.fname); // prints Raj console.log(vm.$data); prints the full object as shown above console.log(vm.$data.fname); // prints Raj If there is a component, the data object has to be referred from a function as shown in the following code. <html> <head> <title>VueJs Introduction</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <script type = “text/javascript”> var _obj = { fname: “Raj”, lname: “Singh”}; // direct instance creation var vm = new Vue({ data: _obj }); console.log(vm.fname); console.log(vm.$data); console.log(vm.$data.fname); // must use function when in Vue.extend() var Component = Vue.extend({ data: function () { return _obj } }); var myComponentInstance = new Component(); console.log(myComponentInstance.lname); console.log(myComponentInstance.$data); </script> </body> </html> In case of a component, the data is a function, which is used with Vue.extend as shown above. The data is a function. For example, data: function () { return _obj } To refer to the data from the component, we need to create an instance of it. For example, var myComponentInstance = new Component(); To fetch the details from the data, we need to do the same as we did with the parent component above. For example. console.log(myComponentInstance.lname); console.log(myComponentInstance.$data); Following are the details displayed in the browser. Props − Type for props is an array of string or object. It takes an array-based or object-based syntax. They are said to be attributes used to accept data from the parent component. Example 1 Vue.component(”props-demo-simple”, { props: [”size”, ”myMessage”] }) Example 2 Vue.component(”props-demo-advanced”, { props: { // just type check height: Number, // type check plus other validations age: { type: Number, default: 0, required: true, validator: function (value) { return value >= 0 } } } }) propsData − This is used for unit testing. Type − array of string. For example, { [key: string]: any }. It needs to be passed during the creation of Vue instance. Example var Comp = Vue.extend({ props: [”msg”], template: ”<div>{{ msg }}</div>” }) var vm = new Comp({ propsData: { msg: ”hello” } }) Computed − Type: { [key: string]: Function | { get: Function, set: Function } } Example <html> <head> <title>VueJs Introduction</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <script type = “text/javascript”> var vm = new Vue({ data: { a: 2 }, computed: { // get only, just need a function aSum: function () { return this.a + 2; }, // both get and set aSquare: { get: function () { return this.a*this.a; }, set: function (v) { this.a = v*2; } } } }) console.log(vm.aSquare); // -> 4 vm.aSquare = 3; console.log(vm.a); // -> 6 console.log(vm.aSum); // -> 8 </script> </body> </html> Computed has two functions aSum and aSquare. Function aSum just returns this.a+2. Function aSquare again two functions get and set. Variable vm is an instance of Vue and it calls aSquare and aSum. Also vm.aSquare = 3 calls the set function from aSquare and vm.aSquare calls the get function. We can check the output in the browser which looks like the following screenshot. Methods − Methods are to be included with the Vue instance as shown in the following code. We can access the function using the Vue object. <html> <head> <title>VueJs Introduction</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <script type = “text/javascript”> var vm = new Vue({ data: { a: 5 }, methods: { asquare: function () { this.a *= this.a; } } }) vm.asquare(); console.log(vm.a); // 25 </script> </body> </html> Methods are part of the Vue constructor. Let us make a call to the method using the Vue object vm.asquare (),
VueJS – Introduction
VueJS – Introduction ”; Previous Next Vue is a JavaScript framework for building user interfaces. Its core part is focused mainly on the view layer and it is very easy to understand. The version of Vue that we are going to use in this tutorial is 2.0. As Vue is basically built for frontend development, we are going to deal with lot of HTML, JavaScript and CSS files in the upcoming chapters. To understand the details, let us start with a simple example. In this example, we are going to use the development verison of vuejs. Example <html> <head> <title>VueJs Introduction</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “intro” style = “text-align:center;”> <h1>{{ message }}</h1> </div> <script type = “text/javascript”> var vue_det = new Vue({ el: ”#intro”, data: { message: ”My first VueJS Task” } }); </script> </body> </html> Output This is the first app we have created using VueJS. As seen in the above code, we have included vue.js at the start of the .html file. <script type = “text/javascript” src = “js/vue.js”></script> There is a div which is added in the body that prints “My first VueJS Task” in the browser. <div id = “intro” style = “text-align:center;”> <h1>{{ message }}</h1> </div> We have also added a message in a interpolation, i.e. {{}}. This interacts with VueJS and prints the data in the browser. To get the value of the message in the DOM, we are creating an instance of vuejs as follows − var vue_det = new Vue({ el: ”#intro”, data: { message: ”My first VueJS Task” } }) In the above code snippet, we are calling Vue instance, which takes the id of the DOM element i.e. e1:’#intro’, it is the id of the div. There is data with the message which is assigned the value ‘My first VueJS Task’. VueJS interacts with DOM and changes the value in the DOM {{message}} with ’My first VueJS Task’. If we happen to change the value of the message in the console, the same will be reflected in the browser. For example − Console Details In the above console, we have printed the vue_det object, which is an instance of Vue. We are updating the message with “VueJs is interesting” and the same is changed in the browser immediately as seen in the above screenshot. This is just a basic example showing the linking of VueJS with DOM, and how we can manipulate it. In the next few chapters, we will learn about directives, components, conditional loops, etc. Print Page Previous Next Advertisements ”;
VueJS – Template
VueJS – Template ”; Previous Next We have learnt in the earlier chapters, how to get an output in the form of text content on the screen. In this chapter, we will learn how to get an output in the form of HTML template on the screen. To understand this, let us consider an example and see the output in the browser. <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “vue_det”> <h1>Firstname : {{firstname}}</h1> <h1>Lastname : {{lastname}}</h1> <div>{{htmlcontent}}</div> </div> <script type = “text/javascript” src = “js/vue_template.js”></script> </body> </html> vue_template.js var vm = new Vue({ el: ”#vue_det”, data: { firstname : “Ria”, lastname : “Singh”, htmlcontent : “<div><h1>Vue Js Template</h1></div>” } }) Now, suppose we want to show the html content on the page. If we happen to use it with interpolation, i.e. with double curly brackets, this is what we will get in the browser. If we see the html content is displayed the same way we have given in the variable htmlcontent, this is not what we want, we want it to be displayed in a proper HTML content on the browser. For this, we will have to use v-html directive. The moment we assign v-html directive to the html element, VueJS knows that it has to output it as HTML content. Let’s add v-html directive in the .html file and see the difference. <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “vue_det”> <h1>Firstname : {{firstname}}</h1> <h1>Lastname : {{lastname}}</h1> <div v-html = “htmlcontent”></div> </div> <script type = “text/javascript” src = “js/vue_template.js”></script> </body> </html> Now, we don’t need the double curly brackets to show the HTML content, instead we have used v-html = ”htmlcontent” where htmlcontent is defined inside the js file as follows − var vm = new Vue({ el: ”#vue_det”, data: { firstname : “Ria”, lastname : “Singh”, htmlcontent : “<div><h1>Vue Js Template</h1></div>” } }) The output in the browser is as follows − If we inspect the browser, we will see the content is added in the same way as it is defined in the .js file to the variable htmlcontent : “<div><h1>Vue Js Template</h1></div>”. Let’s take a look at the inspect element in the browser. We have seen how to add HTML template to the DOM. Now, we will see how to add attributes to the exiting HTML elements. Consider, we have an image tag in the HTML file and we want to assign src, which is a part of Vue. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “vue_det”> <h1>Firstname : {{firstname}}</h1> <h1>Lastname : {{lastname}}</h1> <div v-html = “htmlcontent”></div> <img src = “” width = “300” height = “250” /> </div> <script type = “text/javascript” src = “js/vue_template1.js”></script> </body> </html> Look at the img tag above, the src is blank. We need to add the src to it from vue js. Let us take a look at how to do it. We will store the img src in the data object in the .js file as follows − var vm = new Vue({ el: ”#vue_det”, data: { firstname : “Ria”, lastname : “Singh”, htmlcontent : “<div><h1>Vue Js Template</h1></div>”, imgsrc : “images/img.jpg” } }) If we assign the src as follows, the output in the browser will be as shown in the following screenshot. <img src = “{{imgsrc}}” width = “300” height = “250” /> We get a broken image. To assign any attribute to HMTL tag, we need to use v-bind directive. Let’s add the src to the image with v-bind directive. This is how it is assigned in .html file. <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “vue_det”> <h1>Firstname : {{firstname}}</h1> <h1>Lastname : {{lastname}}</h1> <div v-html = “htmlcontent”></div> <img v-bind:src = “imgsrc” width = “300” height = “250” /> </div> <script type = “text/javascript” src = “js/vue_template1.js”></script> </body> </html> We need to prefix the src with v-bind:src = ”imgsrc” and the name of the variable with src. Following is the output in the browser. Let us inspect and check how the src looks like with v-bind. As seen in the above screenshot, the src is assigned without any vuejs properties to it. Print Page Previous Next Advertisements ”;
VueJS – Rendering
VueJS – Rendering ”; Previous Next In this chapter, we will learn about conditional rendering and list rendering. In conditional rendering, we will discuss about using if, if-else, if-else-if, show, etc. In list rendering, we will discuss how to use for loop. Conditional Rendering Let’s get started and work on a example first to explain the details for conditional rendering. With conditional rendering, we want to output only when the condition is met and the conditional check is done with the help of if, if-else, if-else-if, show, etc. v-if 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 = “showdata” v-bind:style = “styleobj”>Click Me</button> <span style = “font-size:25px;”><b>{{show}}</b></span> <h1 v-if = “show”>This is h1 tag</h1> <h2>This is h2 tag</h2> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { show: true, styleobj: { backgroundColor: ”#2196F3!important”, cursor: ”pointer”, padding: ”8px 16px”, verticalAlign: ”middle”, } }, methods : { showdata : function() { this.show = !this.show; } }, }); </script> </body> </html> Output In the above example, we have created a button and two h1 tags with the message. A variable called show is declared and initialized to a value true. It is displayed close to the button. On the click of the button, we are calling a method showdata, which toggles the value of the variable show. This means on the click of the button, the value of the variable show will change from true to false and false to true. We have assigned if to the h1 tag as shown in the following code snippet. <button v-on:click = “showdata” v-bind:style = “styleobj”>Click Me</button> <h1 v-if = “show”>This is h1 tag</h1> Now what it will do is, it will check the value of the variable show and if its true the h1 tag will be displayed. Click the button and view in the browser, as the value of the show variable changes to false, the h1 tag is not displayed in the browser. It is displayed only when the show variable is true. Following is the display in the browser. If we check in the browser, this is what we get when show is false. The h1 tag is removed from the DOM when the variable show is set to false. This is what we see when the variable is true. The h1 tag is added back to the DOM when the variable show is set to true. v-else In the following example, we have added v-else to the second h1 tag. 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 = “showdata” v-bind:style = “styleobj”>Click Me</button> <span style = “font-size:25px;”><b>{{show}}</b></span> <h1 v-if = “show”>This is h1 tag</h1> <h2 v-else>This is h2 tag</h2> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { show: true, styleobj: { backgroundColor: ”#2196F3!important”, cursor: ”pointer”, padding: ”8px 16px”, verticalAlign: ”middle”, } }, methods : { showdata : function() { this.show = !this.show; } }, }); </script> </body> </html> v-else is added using the following code snippet. <h1 v-if = “show”>This is h1 tag</h1> <h2 v-else>This is h2 tag</h2> Now, if show is true “This is h1 tag” will be displayed, and if false “This is h2 tag” will be displayed. This is what we will get in the browser. The above display is when the show variable is true. Since, we have added v-else, the second statement is not present. Now, when we click the button the show variable will become false and the second statement will be displayed as shown in the following screenshot. v-show v-show behaves same as v-if. It also shows and hides the elements based on the condition assigned to it. The difference between v-if and v-show is that v-if removes the HTML element from the DOM if the condition is false, and adds it back if the condition is true. Whereas v-show hides the element, if the condition is false with display:none. It shows the element back, if the condition is true. Thus, the element is present in the dom always. 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 = “showdata” v-bind:style = “styleobj”>Click Me</button> <span style = “font-size:25px;”><b>{{show}}</b></span> <h1 v-if = “show”>This is h1 tag</h1> <h2 v-else>This is h2 tag</h2> <div v-show = “show”> <b>V-Show:</b> <img src = “images/img.jpg” width = “100” height = “100” /> </div> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { show: true, styleobj: { backgroundColor: ”#2196F3!important”, cursor: ”pointer”, padding: ”8px 16px”, verticalAlign: ”middle”, } }, methods : { showdata : function() { this.show = !this.show; } }, }); </script> </body> </html> v-show is assigned to the HTML element using the following code snippet. <div v-show = “show”><b>V-Show:</b><img src = “images/img.jpg” width = “100” height = “100” /></div> We have used the same variable show and based on it being true/false, the image is displayed in the browser. Now, since the variable show is true, the image is as displayed in the above screenshot. Let us click the button and see the display. The variable show is false, hence the image is hidden. If we inspect and see the element, the div along with the image is still a part of the DOM with the style property display: none as seen in the above screenshot. List Rendering v-for Let us now discuss list rendering with v-for directive. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <div id = “databinding”> <input type = “text” v-on:keyup.enter = “showinputvalue” v-bind:style = “styleobj” placeholder = “Enter Fruits Names”/> <h1 v-if = “items.length>0”>Display Fruits Name</h1> <ul> <li v-for = “a in items”>{{a}}</li> </ul> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { items:[], styleobj: { width: “30%”, padding: “12px 20px”, margin: “8px 0”, boxSizing: “border-box” } },
VueJS – Transition and Animation ”; Previous Next In this chapter, we will discuss the transition and animation features available in VueJS. Transition VueJS provides various ways to apply transition to the HTML elements when they are added/updated in the DOM. VueJS has a built-in transition component that needs to be wrapped around the element, which needs transition. Syntax <transition name = “nameoftransition”> <div></div> </transition> Let us consider an example to understand the working of transition. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <style> .fade-enter-active, .fade-leave-active { transition: opacity 2s } .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ { opacity: 0 } </style> <div id = “databinding”> <button v-on:click = “show = !show”>Click Me</button> <transition name = “fade”> <p v-show = “show” v-bind:style = “styleobj”>Animation Example</p> </transition> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { show:true, styleobj :{ fontSize:”30px”, color:”red” } }, methods : { } }); </script> </body> </html> There is button called clickme created using which we can change the value of the variable show to true to false and vice versa. There is a p tag which shows the text element only if the variable is true. We have wrapped the p tag with the transition element as shown in the following piece of code. <transition name = “fade”> <p v-show = “show” v-bind:style = “styleobj”>Animation Example</p> </transition> The name of the transition is fade. VueJS provides some standard classes for transition and the classes are prefixed with the name of the transition. Following are some standard classes for transition − v-enter − This class is called initially before the element is updated/added. Its the starting state. v-enter-active − This class is used to define the delay, duration, and easing curve for entering in the transition phase. This is the active state for entire and the class is available during the entire entering phase. v-leave − Added when the leaving transition is triggered, removed. v-leave-active − Applied during the leaving phase. It is removed when the transition is done. This class is used to apply the delay, duration, and easing curve during the leaving phase. Each of the above classes will be prefixed with the name of the transition. We have given the name of the transition as fade, hence the name of the classes becomes .fade_enter, .fade_enter_active, .fade_leave, .fade_leave_active. They are defined in the following code. <style> .fade-enter-active, .fade-leave-active { transition: opacity 2s } .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ { opacity: 0 } </style> The .fade_enter_active and .fade_leave_active are defined together and it applies a transition at the start and at the leaving stage. The opacity property is changed to 0 in 2 seconds. The duration is defined in the .fade_enter_active and .fade_leave_active. The final stage is defined in the .fade_enter, .fade_leave_to. The display in the browser is as follows. On the click of the button, the text will fade away in two seconds. After two seconds, the text will disappear completely. Let us consider another example, where there is an image and it is shifted on the x-axis when the button is clicked. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <style> .shiftx-enter-active, .shiftx-leave-active { transition: all 2s ease-in-out; } .shiftx-enter, .shiftx-leave-to /* .fade-leave-active below version 2.1.8 */ { transform : translateX(100px); } </style> <div id = “databinding”> <button v-on:click = “show = !show”>Click Me</button> <transition name = “shiftx”> <p v-show = “show”> <img src = “images/img.jpg” style = “width:100px;height:100px;” /> </p> </transition> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { show:true }, methods : { } }); </script> </body> </html> The name of the transition is shiftx. A transform property is used to shift the image on the x-axis by 100px using the following piece of code. <style> .shiftx-enter-active, .shiftx-leave-active { transition: all 2s ease-in-out; } .shiftx-enter, .shiftx-leave-to /* .fade-leave-active below version 2.1.8 */ { transform : translateX(100px); } </style> Following is the output. On the click of the button, the image will shift 100px towards the right as shown in the following screenshot. Animation Animations are applied the same way as transition is done. Animation also has classes that needs to be declared for the effect to take place. Let us consider an example to see how animation works. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <style> .shiftx-enter-active { animation: shift-in 2s; } .shiftx-leave-active { animation: shift-in 2s reverse; } @keyframes shift-in { 0% {transform:rotateX(0deg);} 25% {transform:rotateX(90deg);} 50% {transform:rotateX(120deg);} 75% {transform:rotateX(180deg);} 100% {transform:rotateX(360deg);} } </style> <div id = “databinding”> <button v-on:click = “show = !show”>Click Me</button> <transition name = “shiftx”> <p v-show = “show”> <img src = “images/img.jpg” style = “width:100px;height:100px;” /> </p> </transition> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { show:true }, methods : { } }); </script> </body> </html> To apply animation, there are classes same as transition. In the above code, we have an image enclosed in p tag as shown in the following piece of code. <transition name = “shiftx”> <p v-show = “show”><img src = “images/img.jpg” style = “width:100px;height:100px;” /></p> </transition> The name of the transition is shiftx. The class applied is as follows − <style> .shiftx-enter-active { animation: shift-in 2s; } .shiftx-leave-active { animation: shift-in 2s reverse; } @keyframes shift-in { 0% {transform:rotateX(0deg);} 25% {transform:rotateX(90deg);} 50% {transform:rotateX(120deg);} 75% {transform:rotateX(180deg);} 100% {transform:rotateX(360deg);} } </style> The class is prefixed with the transition name, i.e. shiftx-enter-active and .shiftx-leave-active. The animation is defined with the keyframes from 0% to 100%. There is a transform defined at each of the keyframes is as shown in the following piece of code. @keyframes shift-in { 0% {transform:rotateX(0deg);} 25% {transform:rotateX(90deg);} 50% {transform:rotateX(120deg);} 75% {transform:rotateX(180deg);} 100% {transform:rotateX(360deg);} } Following is the output. On clicking the button, it rotates from 0 to 360 degree and disappears. Custom Transition Classes VueJS provides a list of custom classes, which can be added
VueJS – Examples
VueJS – Examples ”; Previous Next Example 1: Currency Converter <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <style> #databinding{ padding: 20px 15px 15px 15px; margin: 0 0 25px 0; width: auto; background-color: #e7e7e7; } span, option, input { font-size:25px; } </style> <div id = “databinding” style = “”> <h1>Currency Converter</h1> <span>Enter Amount:</span><input type = “number” v-model.number = “amount” placeholder = “Enter Amount” /><br/><br/> <span>Convert From:</span> <select v-model = “convertfrom” style = “width:300px;font-size:25px;”> <option v-for = “(a, index) in currencyfrom” v-bind:value = “a.name”>{{a.desc}}</option> </select> <span>Convert To:</span> <select v-model = “convertto” style = “width:300px;font-size:25px;”> <option v-for = “(a, index) in currencyfrom” v-bind:value = “a.name”>{{a.desc}}</option> </select><br/><br/> <span> {{amount}} {{convertfrom}} equals {{finalamount}} {{convertto}}</span> </div> <script type = “text/javascript”> var vm = new Vue({ el: ”#databinding”, data: { name:””, currencyfrom : [ {name : “USD”, desc:”US Dollar”}, {name:”EUR”, desc:”Euro”}, {name:”INR”, desc:”Indian Rupee”}, {name:”BHD”, desc:”Bahraini Dinar”} ], convertfrom: “INR”, convertto:”USD”, amount :”” }, computed :{ finalamount:function() { var to = this.convertto; var from = this.convertfrom; var final; switch(from) { case “INR”: if (to == “USD”) { final = this.amount * 0.016; } if (to == “EUR”) { final = this.amount * 0.013; } if (to == “INR”) { final = this.amount; } if (to == “BHD”) { final = this.amount * 0.0059; } break; case “USD”: if (to == “INR”) { final = this.amount * 63.88; } if (to == “EUR”) { final = this.amount * 0.84; } if (to == “USD”) { final = this.amount; } if (to == “BHD”) { final = this.amount * 0.38; } break; case “EUR”: if (to == “INR”) { final = this.amount * 76.22; } if (to == “USD”) { final = this.amount * 1.19; } if (to == “EUR”) { final = this.amount; } if (to == “BHD”) { final = this.amount * 0.45; } break; case “BHD”: if (to == “INR”) { final = this.amount *169.44; } if (to == “USD”) { final = this.amount * 2.65; } if (to == “EUR”) { final = this.amount * 2.22; } if (to == “BHD”) { final = this.amount; } break } return final; } } }); </script> </body> </html> Output (Conversion to USD) Output: Conversion to BHD Explanation − In the above example, we have created a currency converter that converts one value of currency to the selected value of other currency. We have created two dropdowns of currency. When we enter the amount to convert in the textbox, the same is displayed below after conversion. We are using the computed property to do the necessary calculation for currency conversion. Example 2: Customer Details <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> </head> <body> <style> #databinding{ padding: 20px 15px 15px 15px; margin: 0 0 25px 0; width: auto; } span, option, input { font-size:20px; } .Table{ display: table; width:80%; } .Title{ display: table-caption; text-align: center; font-weight: bold; font-size: larger; } .Heading{ display: table-row; font-weight: bold; text-align: center; } .Row{ display: table-row; } .Cell{ display: table-cell; border: solid; border-width: thin; padding-left: 5px; padding-right: 5px; width:30%; } </style> <div id = “databinding” style = “”> <h1>Customer Details</h1> <span>First Name</span> <input type = “text” placeholder = “Enter First Name” v-model = “fname”/> <span>Last Name</span> <input type = “text” placeholder = “Enter Last Name” v-model = “lname”/> <span>Address</span> <input type = “text” placeholder = “Enter Address” v-model = “addr”/> <button v-on:click = “showdata” v-bind:style = “styleobj”>Add</button> <br/> <br/> <customercomponent v-for = “(item, index) in custdet” v-bind:item = “item” v-bind:index = “index” v-bind:itr = “item” v-bind:key = “item.fname” v-on:removeelement = “custdet.splice(index, 1)”> </customercomponent> </div> <script type = “text/javascript”> Vue.component(”customercomponent”,{ template : ”<div class = “Table”><div class = “Row” v-bind:style = “styleobj”><div class = “Cell”><p>{{itr.fname}}</p></div><div class = “Cell”><p>{{itr.lname}}</p></div><div class = “Cell”><p>{{itr.addr}}</p></div><div class = “Cell”><p><button v-on:click = “$emit(”removeelement”)”>X</button></p></div></div></div>”, props: [”itr”, ”index”], data: function() { return { styleobj : { backgroundColor:this.getcolor(), fontSize : 20 } } }, methods:{ getcolor : function() { if (this.index % 2) { return “#FFE633”; } else { return “#D4CA87″; } } } }); var vm = new Vue({ el: ”#databinding”, data: { fname:””, lname:””, addr : ””, custdet:[], styleobj: { backgroundColor: ”#2196F3!important”, cursor: ”pointer”, padding: ”8px 16px”, verticalAlign: ”middle”, } }, methods :{ showdata : function() { this.custdet.push({ fname: this.fname, lname: this.lname, addr : this.addr }); this.fname = “”; this.lname = “”; this.addr = “”; } } }); </script> </body> </html> Output Output after deletion Explanation − In the above example, we have three texboxes to enter – the First Name, Last Name and Address. There is an add button, which adds the values entered in the textboxes in a table format with a delete button. The table format is created using components. The click button interacts with the parent component using the emit event to delete the elemet from the array. The values entered are stored in the array and the same are shared with the child component using the prop property. Print Page Previous Next Advertisements ”;
VueJS – Routing
VueJS – Routing ”; Previous Next VueJS does not have a built-in router feauture. We need to follow some additional steps to install it. Direct Download from CDN The latest version of vue-router is available at https://unpkg.com/vue-router/dist/vue-router.js Unpkg.com provides npm-based cdn links. The above link is always updated to the recent version. We can download and host it, and use it with a script tag along with vue.js as follows − <script src = “/path/to/vue.js”></script> <script src = “/path/to/vue-router.js”></script> Using NPM Run the following command to install the vue-router. npm install vue-router Using GitHub We can clone the repository from GitHub as follows − git clone https://github.com/vuejs/vue-router.git node_modules/vue-router cd node_modules/vue-router npm install npm run build Let us start with a simple example using vue-router.js. Example <html> <head> <title>VueJs Instance</title> <script type = “text/javascript” src = “js/vue.js”></script> <script type = “text/javascript” src = “js/vue-router.js”></script> </head> <body> <div id = “app”> <h1>Routing Example</h1> <p> <router-link to = “/route1”>Router Link 1</router-link> <router-link to = “/route2”>Router Link 2</router-link> </p> <!– route outlet –> <!– component matched by the route will render here –> <router-view></router-view> </div> <script type = “text/javascript”> const Route1 = { template: ”<div style = “border-radius:20px;background-color:cyan;width:200px;height:50px;margin:10px;font-size:25px;padding:10px;”>This is router 1</div>” } const Route2 = { template: ”<div style = “border-radius:20px;background-color:green;width:200px;height:50px;margin:10px;font-size:25px;padding:10px;”>This is router 2</div>” } const routes = [ { path: ”/route1”, component: Route1 }, { path: ”/route2”, component: Route2 } ]; const router = new VueRouter({ routes // short for `routes: routes` }); var vm = new Vue({ el: ”#app”, router }); </script> </body> </html> Output To start with routing, we need to add the vue-router.js file. Take the code from https://unpkg.com/vue-router/dist/vue-router.js and save it in the file vue-router.js. The script is added after vue.js as follows − <script type = “text/javascript” src = “js/vue.js”></script> <script type = “text/javascript” src = “js/vue-router.js”></script> In the body section, there is a router link defined as follows − <p> <router-link to = “/route1”>Router Link 1</router-link> <router-link to = “/route2″>Router Link 2</router-link> </p> <router-link> is a component used to navigate to the HTML content to be displayed to the user. The to property is the destination, i.e the source file where the contents to be displayed will be picked. In the above piece of code, we have created two router links. Take a look at the script section where the router is initialized. There are two constants created as follows − const Route1 = { template: ”<div style = “border-radius:20px;background-color:cyan;width:200px;height:50px;margin:10px;font-size:25px;padding:10px;”>This is router 1</div>” }; const Route2 = { template: ”<div style = “border-radius:20px;background-color:green;width:200px;height:50px;margin:10px;font-size:25px;padding:10px;”>This is router 2</div>” } They have templates, which needs to be shown when the router link is clicked. Next, is the routes const, which defines the path to be displayed in the URL. const routes = [ { path: ”/route1”, component: Route1 }, { path: ”/route2”, component: Route2 } ]; Routes define the path and the component. The path i.e. /route1 will be displayed in the URL when the user clicks on the router link. Component takes the templates names to be displayed. The path from the routes need to match with the router link to the property. For example, <router-link to = ”path here”></router-link> Next, the instance is created to VueRouter using the following piece of code. const router = new VueRouter({ routes // short for `routes: routes` }); The VueRouter constructor takes the routes as the param. The router object is assigned to the main vue instance using the following piece of code. var vm = new Vue({ el: ”#app”, router }); Execute the example and see the display in the browser. On inspecting and checking the router link, we will find that it adds class to the active element as shown in the following screenshot. The class added is class = “router-link-exact-active router-link-active”. The active link gets the class as shown in the above screenshot. Another thing to notice is, the <router-link> gets rendered as a tag. Props for Router Link Let us see some more properties to be passed to <router-link>. to This is the destination path given to the <router-link>. When clicked, the value of to will be passed to router.push() internally. The value needs to be a string or a location object. When using an object, we need to bind it as shown in e.g. 2. e.g. 1: <router-link to = “/route1”>Router Link 1</router-link> renders as <a href = ”#/route”>Router Link </a> e.g. 2: <router-link v-bind:to = “{path:”/route1”}”>Router Link 1</router-link> e.g. 3: <router-link v-bind:to = “{path:”/route1”, query: { name: ”Tery” }}”>Router Link 1</router-link>//router link with query string. Following is the output of e.g. 3. In the URL path, name = Tery is a part of the query string. E.g.: http://localhost/vueexamples/vue_router.html#/route1?name = Tery replace Adding replace to the router link will call the router.replace() instead of router.push(). With replace, the navigation history is not stored. Example <router-link v-bind:to = “{path:”/route1”, query: { name: ”Tery” }}” replace>Router Link 1</router-link> append Adding append to the <router-link><router-link> will make the path relative. If we want to go from the router link with path /route1 to router link path /route2, it will show the path in the browser as /route1/route2. Example <router-link v-bind:to = “{ path: ”/route1”}” append>Router Link 1</router-link> tag At present <router-link> renders as a tag. In case, we want to render it as some other tag, we need to specifty the same using tag = ”tagname”; Example <p> <router-link v-bind:to = “{ path: ”/route1”}” tag = “span”>Router Link 1</router-link> <router-link v-bind:to = “{ path: ”/route2”}” tag = “span”>Router Link 2</router-link> </p> We have specified the tag as span and this is what is displayed in the browser. The tag displayed now is a span tag. We will still see the click going as we click on the router link for navigation. active-class By default, the active class added when the router link is active is router-link-active. We can overwrite the class by setting the same as shown in the following code. <style> ._active{ background-color : red; } </style> <p> <router-link v-bind:to = “{ path: ”/route1”}” active-class