Vue JS

Vue Js Notes

ref link -> https://www.tutorialspoint.com/vuejs/vuejs_instances.htm
{{}} – it is call as ‘interpolations’

Introduction

VueJS is a progressive JavaScript framework used to develop interactive web interfaces.

Features

Virtual DOM, Data Binding, Components, Event Handling, Animation/Transition, Computed Properties, Templates, Directives, Watchers, Routing, Lightweight, Vue-CLI,

Installation

<html>
<head>
http://vue.min.js
</head>
<body></body>
</html>
command line installation also available

Instances (root Vue Instance)

syntax

var app = new Vue({
// options
})

replace predifined element value

<h1 id = “intro”>{{ message }}</h1>

var vue_det = new Vue({
el: ‘h1’,
data: {
message: ‘<?php echo $test;?>’
}
});

call methods in instances

<h1>{{mydetails()}}</h1>

var vm = new Vue({
el: ‘#vue_det’,
data: {
firstname : “Ria”,
lastname : “Singh”,
address : “Mumbai”
},
methods: {
mydetails : function() {
return “I am “+this.firstname +” “+ this.lastname;
}
}
})

computed

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.athis.a;
},
set: function (v) {
this.a = v
2;
}
}
}
})

get value by vm.aSquare to get value from get function
vm.aSquare to set function
vm.aSum return sum function

Templace

load html inside element

in instance data add -> htmlcontent : ”

Vue Js Template

load src of img element

<img v-bind:src = “imgsrc” width = “300” height = “250” />

in instance data add -> imgsrc : “images/img.jpg”

Components

Components are one of the important features of VueJS that creates custom elements, which can be reused in HTML.

Vue.component(‘testcomponent’,{
template : ‘

This is coming from component


});
var vm = new Vue({
el: ‘#component_test’
});

use components inside instance

var vm = new Vue({
el: ‘#component_test’,
components:{
‘testcomponent’: {
template : ‘

This is coming from component


}
}
});

use dynamic data and methods in component

template : ‘

Custom Component created by {{name}}

‘,
data: function() {
return {
name : “Ria”
}
},
methods:{
changename : function() {
this.name = “Ben”;
},
originalname: function() {
this.name = “Ria”;
}
}

to add events in elements user v-on:eventname = action

Dynamic Components

<component v-bind:is = “view”></component>
<component v-bind:is = “view1”></component>

var vm = new Vue({
el: ‘#databinding’,
data: {
view: ‘component2’,
view1: ‘component3’,
},
components: {
‘component2’: {
template: ‘

Test Component


},
‘component3’: {
template: ‘

Test Component


}
}
});

load templates in view

Computed Properties

Its like method but difference is method return different values when we call each time but computed property returns same results to all calls

eg: get randrom numbers from method return different value each time but computed property return same value
call computed function “{{getrandomno1()}}”

*v-model is used to bind input value to variable

Get/Set in Computed Properties

get is used to return calculated value to bind variable

computed :{
fullname : {
get : function() {
return this.firstName+” “+this.lastName;
},
set : function(name) {
var fname = name.split(” “);
this.firstName = fname[0];
this.lastName = fname[1];
}
}
}

set is used to assign value to computed property using “vm.fullname = ‘Thanks Kannan'”

computed property can be call without get and set like method

Watch Property

watch is used to change input boxes depend on another input box value on change
eg: when changing kilometers value meters value automatically change and change meters value kilometers value automatically change
watch : {
kilometers:function(val) {
this.kilometers = val;
this.meters = val * 1000;
},
meters : function (val) {
this.kilometers = val/ 1000;
this.meters = val;
}
}

Binding

Binding variable -> {{title}}

data: {
title : “DATA BINDING”,
}
Binding href -><a v-bind:href = “hreflink” target = “_blank”>Click Me </a>

data: {
hreflink : “http://www.google.com&#8221;
}

binding isactive class -> div v-bind:class = “{active:isactive}”>

data: {
isactive : true
}

We can also assign multiple classes

v-bind:class = “{ active: isActive, ‘displayError’: hasError }”

data: {
isActive : false,
hasError : false
}

We can also pass class as an array

<

div>

data: {
infoclass : ‘info3’,
errorclass : ‘displayError’,
}

we can also assign class like if or else

<

div>

isActive tru infoclass else ” will display

?need clarification in how to bind class in component templates

Binding Inline Styles

<

div>

data: {
activeColor: ‘red’,
fontSize :’30’
}

We can also do the same thing by assigning all the values to a variable

<

div>

data: {
styleobj : {
color: ‘red’,
fontSize :’40px’
}
}

Form Input Bindings

used in input default values and show values onchange

Modifiers
We have used three modifiers in the example – trim, number, and lazy.

modifiers are used to change values entering in input fields
trim – remove empty spaces start and end of values
number – remove non numbers
lazy – show changed values after on blur

?need clarification in number modifier its not working correctly with type input

Events

v-on is the attribute added to the DOM elements to listen to the events in VueJS.

Click ME

methods : {
displaynumbers : function(event) {
console.log(event);
return this.total = this.num1+ this.num2;
}
},

shorthand for v-on: is @
eg Click ME

Event Modifiers

We need to add dot operator while calling the modifiers
Click Once
.once – Allows the event to execute only once.

Click Me
.prevent – link not open only function will execute

Event – Key Modifiers

VueJS offers key modifiers based on which we can control the event handling.

keyup event work when enter key press

Custom Events

this.$emit(‘showlanguage’, lng); used to call custom event, lng is argument

declare custom event as below

languages : [“Java”, “PHP”, “C++”, “C”, “Javascript”, “C#”, “Python”, “HTML”] for items in lauguages

v-for means for loop for items in lauguages

$emit is used to call the parent component method.

?need full understanding

Rendering

Conditional Rendering

Its like true or false condition to add or remove values

v-if

This is h1 tag

value added only if show is true otherwise it remove

v-else

This is h1 tag

This is h2 tag

if show true h1 visible else h2 visible

v-show

v-show behaves same as v-if. difference is v-if remove and add element and v-show hide and show element (display:none)

<

div>

List Rendering

v-for

  • {{a}}
  • repeat items array as value as a .

    we can use value and index as below

  • {{index}}–{{a}}
  • were a is value and index is key.index come like 0,1,2,3….

    Transition

    VueJS has a built-in transition component that needs to be wrapped around the element, which needs transition.

    Syntax

    </transition>

    eg:
    <transition name = “fade”>
    <p v-show = “show” v-bind:style = “styleobj”>Animation Example</p>
    </transition>

    but need to add css also for each transition

    css name transition name should use same name

    eg

    css for transition fade

    .fade-enter-active, .fade-leave-active {
    transition: opacity 2s
    }
    .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
    opacity: 0
    }

    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.

    Animation

    Animations are applied the same way as transition is done.

    Custom Transition Classes

    Custom classes basically come into play when we want to use an external CSS library such as animate.css.

    <transition
    name = “custom-classes-transition”
    enter-active-class = “animated swing”
    leave-active-class = “animated bounceIn”>
    <p v-if = “show”><span style = “font-size:25px;”>Example</span></p>
    </transition>

    animated swing and animated bouncein are third party css animation we add it while enter-active-class and leave-active-class

    Explicit Transition Duration

    <transition :duration = “1000”></transition>
    <transition :duration = “{ enter: 500, leave: 800 }”>…</transition>

    JavaScript Hooks

    The transition classes can be called as methods using JavaScript events.
    it means animation using js methods

    Transition at the Initial Render

    In order to add animation at the start, we need to add ‘appear’ property to the transition element.
    it means animation work when element initiated

    eg:
    <transition
    appear
    appear-class = “custom-appear-class”
    appear-active-class = “animated bounceIn”>
    <h1>BounceIn – Animation Example</h1>
    </transition>

    Animation on Components

    <transition appear
    appear-class = “custom-appear-class”
    appear-active-class = “animated wobble”>
    <component v-bind:is = “view”></component>
    </transition>

    Directives

    Directives are instruction for VueJS to do things in a certain way.
    v-if, v-show, v-else, v-for, v-bind , v-model, v-on, etc.

    custom directives

    suntax
    Vue.directive(‘nameofthedirective’, {
    bind(e1, binding, vnode) {
    }
    })

    VueJS Directive

    eg:
    Vue.directive(“changestyle”,{
    bind(e1,binding, vnode) {
    console.log(e1);
    e1.style.color = “red”;
    e1.style.fontSize = “30px”;
    }
    });

    in this example we created a directive call changestyle and change style of the element

    Filters

    filters that help with text formatting.it is used along with v-bind and interpolations ({{}}). We need a pipe symbol at the end of JavaScript expression for filters.

    <input v-model = “name” placeholder = “Enter Name” /><br/>

    {{name | countletters}}

    filters : {
    countletters : function(value) {
    return value.length;
    }
    }

    this will return length of characters in input

    Routing

    we need to install vue-router.js
    we can done this by direct download or user npm “npm install vue-router” or useing github “git clone https://github.com/vuejs/vue-router.git node_modules/vue-router
    cd node_modules/vue-router
    npm install
    npm run build”

    router link is defined as below

    <router-link to = “/route1”>Router Link 1</router-link>
    <router-link to = “/route2”>Router Link 2</router-link>

    initialize route as below

    const Route1 = { template: ‘

    This is router 1

    ‘ };
    const Route2 = { template: ‘

    This is router 2

    ‘ }

    defines path to route

    const routes = [
    { path: ‘/route1’, component: Route1 },
    { path: ‘/route2’, component: Route2 }
    ];

    next route instance

    const router = new VueRouter({
    routes // short for routes: routes
    });

    next assign route to vue instance

    var vm = new Vue({
    el: ‘#app’,
    router
    });

    Props for 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.

    <router-link to = “/route1”>Router Link 1</router-link>
    <router-link v-bind:to = “{path:’/route1′}”>Router Link 1</router-link>

    replace

    Adding replace to the router link will call the router.replace() instead of router.push(). With replace, the navigation history is not stored.

    append

    <router-link v-bind:to = “{ path: ‘/route1’}” append>Router Link 1</router-link>

    it will append to previous route as /route1/route2.

    active-class

    By default, the active class added when the router link is active is router-link-active.

    <router-link v-bind:to = “{ path: ‘/route1’}” active-class = “_active”>Router Link 1</router-link>

    exact-active-class

    The default exactactive class applied is router-link-exact-active. We can overwrite it using exact-active-class.

    <router-link v-bind:to = “{ path: ‘/route1’}” exact-active-class = “_active”>Router Link 1</router-link>

    event

    At present, the default event for router-link is click event. We can change the same using the event property.

    <router-link v-bind:to = “{ path: ‘/route1’}” event = “mouseover”>Router Link 1</router-link>

    Mixins

    Mixins are basically to be used with components. They share reusable code among components.

    simple example
    var mixin = {
    methods: {
    hellworld: function () {
    alert(‘In HelloWorld’);
    },
    samemethod: function () {
    alert(‘Mixin:Same Method’);
    }
    }
    };
    var vm = new Vue({
    mixins: [mixin],
    methods: {
    start: function () {
    alert(‘start method’);
    },
    samemethod: function () {
    alert(‘Main: same method’);
    }
    }
    });
    vm.hellworld();
    vm.start();
    vm.samemethod();

    we can join mix with another vue instance . if methods are same name main vue instance take priority

    ? need clarification in using mix with components

    Render Function

    we can convert same component and reuse it.

    <testcomponent>Hello Jai</testcomponent>
    <testcomponent>Hello Roy</testcomponent>
    <testcomponent>Hello Ria</testcomponent>
    <testcomponent>Hello Ben</testcomponent>

    template : ‘<h1><slot></slot></h1>’,

    Reactive Interface

    It is added dynamically to already created vue instance.

    vm.$watch(‘counter’, function(nval, oval) {
    alert(‘Counter is incremented :’ + oval + ‘ to ‘ + nval + ‘!’);
    });

    this wil add watch to the vue instance vm.

    Vue.set

    This method helps to set a property on an object.

    Vue.set( target, key, value )

    vm.products.qty = “1”;

    Vue.set(myproduct, ‘qty’, 1);

    Vue.delete

    Vue.delete( target, key )

    Vue.delete(myproduct, ‘price’);

    it will delete a property of object myproduct

    Advertisements
    Regex

    Regex Syntax

    reference link->https://regexone.com/

    \d – any numbers
    \D – any non numbers
    \ – The preceding slash distinguishes it from the simple character and indicates that it is a metacharacter.
    skip metacharacter and take it as character user \ before metacharacter for . or ?
    …. – math values(cat. AND 896. AND ?=+. )
    [can] – a letter can either be c or a or n
    [^can] – a letter cannot be c or a or n
    [^b]og – meaning -> a letter cannot be b AND remaining matches ‘og’
    [hd]og – meaning -> a letter can be h or d AND remaining matches ‘og’
    [a-z] – a letter can between a to z with case sensitive
    [A-Z] – a letter can between A to Z with case sensitive
    [^D-Z] – a letter cannot between D to Z with case sensitive
    [^a-d] – a letter cannot between a to d with case sensitive
    [A-Za-z0-9] – a letter can between A to Z or a to z or 0 to 9
    [^A-Za-z0-9] – a letter cannot between A to Z or a to z or 0 to 9
    [\w] – a letter can be all alphanumeric character (same as [A-Za-z0-9_])
    [^\w] , [\W]- a letter cannot be all alphanumeric character (same as [^A-Za-z0-9_])
    c{3} – no of repetitive letter 3 times c
    [wxy]{4} – no of repetitive letter 4 times either w or x or y
    [w]{3,5} – no of repetitive letter 3 times to 5 times only w
    [^\d]+ – remaining all character cannot contain number
    [abc]+ – remaining can contain a or b or c
    a{2,4}[^a]+ – meaning -> start with ‘a’ repetitive of 2 to 4 times and remaining cannot contain ‘a’
    abc+ – meaning -> remaining value should have abc
    . – a letter can be any character
    .{1,10} – a letter can be any character repetitive of 1 to 10 times
    .* – zero or more of any character
    [a]{2,4}.* – meaning – > start with ‘a’ repetitive of 2 to 4 times and remaining zero or more of any character
    v? – either contain char v or not (example – files? -> either file or files success)
    \s – any whitespace
    \S – any non whitespace
    \t – tab (whitespace)
    \n – new line (whitespace)
    ^Mission: successful$ – match entire line

    match particular format example(^file_[\w]+[\w]+.pdf$ -> meaning should start with word ‘file‘ and continue with any string with any repetitive times and should contain _ after that and continue with any string with any repetitive times and should end with ‘.pdf’)

    () – used to define group

    differce between .+ and .* -> .+ one or more characters, .* zero or more characters

    | – useing for OR operator example (I love (cats|dogs) -> cats OR dogs)