Vue Js

Important Command in VUE 

  •  How to install NPM in Vue JS 

  1. Open Node CMD => open the project location 
  2. run the command => npm install 

  • How to check the version of Vue 
        vue --version

  • Install Vue CLI

        npm install -g @vue/cli

        VS automatically run the server for vue project 

  • To run the Vue project 

        npm run server

  • To install npm package 

          npm install npm_package_name

  • To create component 

        there is no specific command to create component in vue yet 

Important VUE site 

https://vuejs.org/guide/introduction.html
https://cli.vuejs.org/#getting-started
https://vuejs.org/api/#data

Points To be remember

  1. As compared to angular and react, in Vue we don't have multiple files for single component (i.e., HTML, CSS, TS). In Vue have single file for single component ending with extension .vue. And we will write our styling and script as well as component template in single file.
  2. File name should start with upper case and extension with lower case.

Control Flow of Vue UI

Inside the public folder there is Index.html file which contains one empty <Div> having Id="app" which is further used by Vue to inject the UI/ Component. 
 <div id="app"></div>

 Index.html =>                                                                             
                           <divid="app</div>  
                          ==> createApp(App).mount('#app')
                           =>Component Referred to 

Main.Js

import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

The line createApp(App).mount('#app') means => createApp is used to inject our App component in Index.html and is mount('#app') telling us where exactly we will inject it (means we will replace the <div> having Id="app"). 

app.Vue

app.Vue is the main vue file which will be injected inside our index.html file. 

Vue Component

In vue, a component represents a portion of UI that will render over the screen whenever called.  
For example The header is a portion of the UI that will remain almost same for most of the webpages, so we can create a component of the Header and that can be called for all the webpages with header on them. 

Vue component is divided into three parts, 
  • Template: contains HTML code that will be injected in DOM whenever the component is called 
  • Script: contains the vue code (Written over JS) it will provide the logic to our UI code
  • Style: Contains the CSS code that will provide the styling to our component 

Important point to remember while creating components 

  • Register/Add the component in app.js after creating it, to use it throughout the vue application

Global Styling 

We can add styling inside the component from outside the component file using import in style tag 
 So, instead of writing styling for each component we can write the styling in one page, and we can import the css in app.Vue component. 

Example: create file Style.css in Assest folder and add reference in app.Vue as mentioned below: 
<style>
 @import "assets/CustomStyle.css";
</style>

We can also import the style.css file in app.Vue file, such as if we have imported npm bootstrap package, then we can include bootstrap in our project in app.Vue file as below: 

import "../node_modules/bootstrap/dist/css/bootstrap.min.css"

Routing 

In vue to apply routing, install vue-router

npm install vue-router

to check you can see in package.json => under dependency => 
"dependencies": {                                                                                                                                        
    "core-js": "^3.6.5",                                                                                                                                  
    "vue": "^3.0.0",                                                                                                                                       
    "vue-router": "^4.1.6"                                                                                                                         
  }                                                                                                                                                                
    
you can create a separate file for routing in src/router/index.js 
and can add/import a file in main.js

import router from './router/index'
createApp(App).use(router).mount('#app')

In the above way, we can add our own routing in root file, i.e. main.js

Routing Array: 

Routing Array and Its array element object 
const routes = [
    {
        path: "/",
        name: "Home",
        component: Home,
    },
    {
        path: "/about",
        name: "About",
        component: About,
    },
];

routing array element object has three properties as below 
  • path:  URL path where this route can be found
  • name:  an optional name to use when we link to this route.
  • component: which component to load when this route is called

 <router-view/>

  • Using <router-view/> we can change or rotate our component to the UI based on the current route
  • <route-view/> work along side with route 

 Authenticate Route

we can authenticate the route in out main route page with the help o the route property known as beforeEnter which accept the function 

beforeEnter property accept function with three parameter as mentioned below 
  1. to : the target route location
  2. from : the current route location
  3. next : if we want to redirect than we can use this. 

How to redirect from Script

                    this.$router.push("/redirect-path")

Nested Route

We can use the lazy loading to navigate to child component. 

we can use one of the properties of the route object as children which defines the children/sub route of the main route 

Note we can create multiple nested route, that depends on the requirement. 

Example: 
const routes = [{
        path: "/usermanagement",
        name: "usermanagement",
        beforeEnter: CheckUserLogin,
        component: userManagement,
        children: [
            {
                path: "/usermanagement/addUser",
                name: "usermanagement",
                beforeEnter: CheckUserLogin,
                component: addUser,
            } ]
    }];
 

Go Back To Previous route 

this.$router.back();

Export Default 

Export default is an 

Option Api

  • name: Name of the component, also used as a selector to render the view of component in application 
  • data(): is function which will return all the property/variable that can we used in the template using interpolation
                          data() {

                                        return {
                                                
                                                   };
                                    }
  • the above code could be written as 
                         data:()=>( {
                                             employeeName:'Manish'
                                          })
Note that if you use an arrow function with the data property, this won't be the component's instance, but you can still access the instance as the function's first argument:

 After the instance is created, the reactive data object can be accessed as this.$data.
  • methods: in Option api method will contain all the function/method that will be used inside the corresponding component.  
                        methods: {
                                myFunction() {
                                            alert('I have created one method')
                                        },
                                        myfunction2() {
                                            alert('I have created second method')
                                        }
                                    }
  • mounted:
                       mounted() {
                            console.log('Hello world ')
                                    }  
  • props: 
    • porps is used to get the parent to child changes in the vue.  
    • Props are read-only and cannot be modified by the child component because the parent component "owns" that value.
    • multiple props can be appended to the component in the array of props.
export default {
  props: ['name']
} 
    • props: we can create the object of props to restrict the datatype of the props using below syntax 


export default{

                                props : {
                                        name :String                
                                   }
                                          }
    • Setting up the default value : In case parent donot pass any any value to its child tha we can set some default value to the props.
props :{
            name :{
                    type: String,
                    required: true,
                    default: "Stubborn"
                }
    

Composition API

Composition API allows you to group code logic together inside a setup() function.


important points :
      • Composition api is typically used with <script setup> 
Some Composition API:
  • setup():The setup() function enables you to extract parts of components and group them logically together. It helps you wrap your logic stored in the form of a function. It accepts props and the context object (with which you can emit events and data) as optional arguments. The setup() function returns state and other defined variables so that the component’s template can access them.
import { reactive } from 'vue'

export default {
  setup() {
    const state = reactive({ count: 0 })

    function increment() {
      state.count++
    }

    // don't forget to expose the function as well.
    return {
      state,
      increment
    }
  }
}

Event Handling 

we can use v-on directive to handle the event in vue template, or we can use @ instead on v-on for shorthand. 

Example:
        <button v-on:click="count++">Add 1</button>
        <button @click="count++">Add 1</button>
Or
         <button v-on:click="addCount">Add 1</button>
        <button @click="addCount">Add 1</button>


Event Handling Event

we can have our event handling login inside the methods API(One of the Option API))

Example:
        
        <button @click="greet('Hello World')">Greeting</button>

        methods: {                  greet(message) {                  // `this` inside methods points to the current active instance                        alert(message)             }             }             }


Emitting Custom event from Child to Parent

to emitting of event from child is done so that parent can perform any action whenever child emit the event. 

to emit the event we use one of the vue object i.e. 
                        this.$emit('event-name','value passed to that event ')

  • event name: parent will listen to child event on this event name. for example :<ChildComponent @event-name="event-handler"/>
  • Values passed to that event: we can pass only one parameter with the event, so If we have any case where we need to send multiple values with event that we can aggregate all the values in a object and we can pass that object to that event. 
    • we can pass string, number , object, boolean, function as parameter with event.
    method: {
        event-handler(values){
                        console.log('values/ parameter of the event ',values)
                         }
                  }

Form Binding

In vue, we use v-model to bind the form with our code.

using v-model we can provide two way binding to our from inputs.

Example:
            <form>
                <input v-model="loginForm.username" type="text" id="username" class="fadeIn second" name="username" placeholder="Enter login">
                <input v-model="loginForm.password" type="text" id="password" class="fadeIn third" name="password" placeholder="Enter password">
                <input type="button" @click='login' class="fadeIn fourth" value="Log In">
            </form>


        export default {         name: 'login',         data() {         return {          loginForm: {         username:'',         password:''         }         }         },
        }


LifeCycle Hook

  • Created: Created is hook which is called whenever the component is called.

Template Refs

template refs is used to refer the particular DOM element into our Vue. 
IT is similar to getElementById() is JS and ViewChild() in angular. 

Syntax:
<template>
                   <confirm-dialogue ref="confirmDialogue"></confirm-dialogue>
</template>

<script>
    import ConfirmDialogue from '../../Shared/ConfirmPopUp.vue'
    export default {
        name: 'login',
        components: {
            ConfirmDialogue
        },
        methods: {
                async confirm() {
                            console.log(this.$refs)
                            const ok = await this.$refs.confirmDialogue.show({
                            title: 'Confirm Pop-up ',
                            message: 'Are you sure you confirm.',
                            okButton: 'ok',
                            cancelButton:'Cancel'
                            })

                        if (ok) {
                                alert('You have successfully delete this page.')
                                } else {
                                }
            }
    }
}

Important Points:
  • If ref is used on the child component the it will refer to child component instance. 

Pinia

Pinia is vue library used to mention the state of the component. We can call it as state management
technique. it allows you to share a state across components/pages.

Below command is used to install the pinia 

npm install pinia

Pinia is use to create a store that can be accessed globally by other component also. It is safe to say that, pinia store is similar to services in angular.

We can save all the code the need to be access by multiple component, then we can use pinia store

Note:     
  • It is recommended to use separate folder to store the store files 
  • Create your store file inside this folder that can be globally used from here.
  • to use the pinia import definestore from pinia
Similar to Vue's Options API, we can also pass an Options Object with state, actions, and getters properties.

You can think of state as the data of the store, getters as the computed properties of the store, and actions as the methods.

Defining a store
  • A store is defined using defineStore()
  • for each store, there should be a unique name so that pinia can access  it globally. 
  • state: is used to hold all the property that can be used by store,
    • state can hold all the property of the store and using getter you can modify the state property and return to its caller. 
  • getters:  using getter you can modify the state property and return to its caller. 
  • actions: action is similar to method which has the ability to perform some action like change the state etc. 

Axios

  • A promise based HTTP client
  • To install axios in you project use below command
npm install axios
axios
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => (this.info = response.data))
.catch(error => console.log(error))

Built-in component

<Slot> 

a slot tag will reserve the space in child component template so that the can parent can enter its own DOM with in it.

The <slot> element is a slot outlet that indicates where the parent-provided slot content should be rendered. 

<Transition>

Transaction is used for applying animations when an element or component is entering and leaving the DOM. This is covered on this page.

there are six classes in transition which we can use to adjust the transition as per our condition as mentioned below:
  1.  v-enter-from : applied when element is inserted into DOM
  2. v-enter-to: applied when element had completely inserted into DOM.
  3. v-enter-active: applied when element is transition state from v-enter-from to v-enter-to 
  4. v-leave-from: applied when element is leaving from DOM
  5. v-leave-to: applied when element  had completely leaved from DOM.
  6. v-leave-active: applied when element is transition state from v-leave-from to v-leave-to 

Form Validation 

For form validation, most popular package to be used is vee-validate 

vee-validate 

Field: Name is mandatory for a feild 



0 Comments