Skip to main content

Vue.js Sample For Beginners

Introduction:

Vue.Js is a front-end progressive javascript framework. Vue.Js is one of the most widely used javascript frameworks. It is a very light-weight or skinny framework, which downloads very fastly on all most all modern browsers. It can be used in both multi-page and single-page applications.

Getting Started:

Let's start learning Vue.Js by hands-on by creating a single-page sample application by referring to all basic features in it. Create a folder to store sample application files, add an 'index.html' file and 'app.js'(maintain Vue.Js Code) file and refer Vue.Js CDN link on the index.html and for UI design let's refer Bootstrap links on the index.html page.
index.html:
<html>
  <head>
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
  </head>
  <body>
    <script
      src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
      integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
      integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
      integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
      crossorigin="anonymous"
    ></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="app.js"></script>
  </body>
</html>

Vue Instance And It's Options:

Vue.Js application starts by creating an instance of  'Vue' with the 'new Vue({})' function which takes javascript object literal as input parameters which can be called options to Vue function.
Example:
var app = new Vue({
    el: '#app',
    data:{
        message:'hello'
    },
    // more options like methods, life cycle function, 
    // computated properteis,registering components
})
Here example shows how to create an instance of 'Vue' and then options passed to the Vue function in an example like 'el' and 'data'.
Now let's create a Vue instance in our sample application.
Add below the Html code in index.html file:
<div id="app">
   {{ message }}
</div>
Add below code to app.js file:
var app = new Vue({
  el: "#app",
  data: {
    message: "Hello Vue!"
  }
});
  • Here 'new Vue({})' creates an instance of Vue. 
  • 'el' refers to the Html element, it gives control over the Html tag to Vue for data manipulation and trigger events. Value it takes 'id' of an Html element.
  • 'data' object works with Vue's reactivity system, data object properties hold the application information to display and on change in data in data object Html gets re-rendered by the principle of Vue's reactivity. 'message' is a property it holds data and observe the Html above {{message}}(Binding Interpolation) , value in the 'message' property get rendered on Html on loading the page. 
Now to test the sample application by loading index.html page, we can see 'message' property in the data object, its value gets rendered on the Html page

Axios Plugin:

Promise based HTTP client libraries for browsers to consume the Rest API. Click here to reach Axios.
Add below script tag to 'index.html' file and it should be above our Vue file 'app.js' to avoid undefined issues(Note: any third party library js file should run before our application js files).
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Axios Example:
axios({
  method: 'get',
  url: 'http://myapi',
})
.then(function (response) {
});
  • Axios is a function which takes javascript object literal is an input parameter it can be called as Axios configuration. 
  • 'method' represents Http verbs like 'GET', 'POST', 'PUT' and 'DELETE'. 
  • 'url' represents the Rest API path. 
  • Axios returns a promise, a call back function passed as input parameter to the promise to catch the response from API.

Mounted Vue Js:

mounted() function is one of the life cycle methods of Vue.Js. mounted() is called when DOM has mounted so we can access the components, templates and DOM elements. In any application to display data, we need to call an API, in Vue we are going to consume all initial or page load API's in mounted function because this function automatically gets triggered once DOM has to get ready to render.

Consume API From Mounted Function:

Now in our sample going to consume API which returns a list of cricketers, in Vue mounted function.
                                 I'm Using Dotnet Core API in the sample
Update the 'app.js' as below:
var app = new Vue({
  el: "#app",
  data: {
    message: "Hello Vue!"
  },
  mounted:function(){
     axios({
       method: 'get',
       url: 'https://localhost:44316/api/player/all'
     }).then(function(response){
        console.log(response.data);
     })
  }
});
Now load the 'index.html' and then mounted function automatically get executed and consumes API using Axios and in-browser console we can see the results.

v-for Directive:

Vue.Js rendering collection of items in Html by v-for Directive.
Example:
<div id="example">
  <ul>
 <li v-for="item in items">{{item.Text}}</li>
  </ul>
</div>

Template Element:

  • <template/> element is a virtual element, which helps in rendering block of the element on using condition directive 'v-if' or looping directive 'v-for'. 
  • All the elements inside the template element get render, but the template element itself won't render in Html. 
  • v-for and v-if directives some times create a scenario to use both of them, but both directives can't be used on a single element at the time template tag very handy.
<template v-for="item in itemList">
  <div>
 Some Content
  </div>
</template>

API Data Binding To A Html Template:

In Vue.JS binding like eg: '{{property_from_data_object}}' is called Data Interpolation Binding. Now update the Html element with id 'app' in 'index.html' as below
index.html:
<div id="app">
  <div class="row">
 <template v-for="player in players">
   <div class="col-sm-4">
  <div class="card">
    <img src="player.jpg" class="card-img-top" />
    <div class="card-body">
   <h4 Card-title>{{player.firstName}} {{player.lastName}}</h4>
    </div>
    <ul class="list-group list-group-flush">
   <li class="list-group-item">
     <div class="row">
    <div class="col-sm-6">
      Age
    </div>
    <div class="col-sm-6">
      {{player.currentAge}}
    </div>
     </div>
   </li>
   <li class="list-group-item">
     <div class="row">
    <div class="col-sm-6">
      Playing Role
    </div>
    <div class="col-sm-6">
      {{player.playingRole}}
    </div>
     </div>
   </li>
   <li class="list-group-item">
     <div class="row">
    <div class="col-sm-6">
      Batting Style
    </div>
    <div class="col-sm-6">
      {{player.battingStyle}}
    </div>
     </div>
   </li>
   <li class="list-group-item">
     <div class="row">
    <div class="col-sm-6">
      Bowling Style
    </div>
    <div class="col-sm-6">
      {{player.bowlingStyle}}
    </div>
     </div>
   </li>
    </ul>
    <div class="card-body">
   <a href="#" class="btn btn-primary">Edit</a>
   <button class="btn btn-danger">Delete</button>
    </div>
  </div>
   </div>
 </template>
  </div>
</div>
Here binding list of 'players' by looping with the help of v-for directive on 'template' element(a virtual element which won't be rendered on the DOM).

Since we are using 'players' property in binding it should be present in 'data object' in our Vue.Js file, and assign the data from API to the 'players' property. Since the properties of 'data object' are reactive which re-renders the Html template on every change in the property which is the Vue Reactive System principle. Now update the 'app.js' as below
app.js:
 var app = new Vue({
  el: "#app",
  data:function() {
    return{
      players:[]
    }
  },
  mounted:function(){
     axios({
       method: 'get',
       url: 'https://localhost:44316/api/player/all'
     }).then((response) => {
       this.players = response.data;
     })
  }
});
Now open 'index.html' on the browser and test the data binding

Vue Components:

  • Components are reusable Vue instances, its initialization syntax will be different but more or less another way of creating Vue. So all the properties available by creating Vue instance like 'new View({})' are available in the Vue component also. 
  • The component gets created with a name, to render this component custom element tag which matches the name of the component will be placed on HTML. 
  • 'props' in component holds the data passed by the component parent, this 'props' helps to render the dynamic content in the component. 
  • 'template' property in component holds the Html content that will be displayed on using the component.
Example Vue Syntax:
Vue.component('school',{
  props:['student'],
  template:`
  <h1>{{student.name}}</h1>
  `
})
Example Html Syntax:
<school v-bind:student="student"></school>

Update Sample Application Display Data To Vue Component:

Update the 'index.html' as below:
<div id="app">
  <circket-players v-bind:players="players"></circket-players>
</div>
'cricket-players' is a custom element tag, which renders the Vue component. Hereby using attribute binding directive 'v-bind' passing data to the component.

Add the piece of code below into 'app.js':
var cricketerComponent = Vue.component('circket-players',{
  props:['players'],
  template: `
  <div class="row">
        <template v-for="player in players">
          <div class="col-sm-4">
            <div class="card">
              <img src="player.jpg" class="card-img-top" />
              <div class="card-body">
                <h4 Card-title>{{player.firstName}} {{player.lastName}}</h4>
              </div>
              <ul class="list-group list-group-flush">
                <li class="list-group-item">
                  <div class="row">
                    <div class="col-sm-6">
                      Age
                    </div>
                    <div class="col-sm-6">
                      {{player.currentAge}}
                    </div>
                  </div>
                </li>
                <li class="list-group-item">
                  <div class="row">
                    <div class="col-sm-6">
                      Playing Role
                    </div>
                    <div class="col-sm-6">
                      {{player.playingRole}}
                    </div>
                  </div>
                </li>
                <li class="list-group-item">
                  <div class="row">
                    <div class="col-sm-6">
                      Batting Style
                    </div>
                    <div class="col-sm-6">
                      {{player.battingStyle}}
                    </div>
                  </div>
                </li>
                <li class="list-group-item">
                  <div class="row">
                    <div class="col-sm-6">
                      Bowling Style
                    </div>
                    <div class="col-sm-6">
                      {{player.bowlingStyle}}
                    </div>
                  </div>
                </li>
              </ul>
              <div class="card-body">
                <a href="#" class="btn btn-primary">Edit</a>
                <button class="btn btn-danger">Delete</button>
              </div>
            </div>
          </div>
        </template>
      </div>
  `
});

Now once again test the application, we can observe it work as previously.

'methods' In Vue:

'methods' is an option passed to the Vue instance, it holds javascript object literal with functions as value to each property. These 'method' functions are a block of code used in splitting code,  events functions, call back functions, etc.
Example:
var app = new Vue({
  el:"#app",
  methods:{
    add:function(){
      // do something
    },
    delete:function(){
      // do something
    }
  }
})

Events (v-on directive):

Listening to DOM events can be done with 'v-on' directive provided by Vue. To listen to an event, we need to bind function in 'methods'.
Example:
var app = new Vue({
  el:"#app",
  methods:{
    add:function(){
      // it get executed on  clicking add button
    },
  }
})
<div id="app">
  <button v-on:click="add()">Add</button>
</div>

Event Communication Between Child To Parent:

Most of the time we may encounter situations like sending data from Vue child component to parent component, to do that Vue provided an event emitter '$emit('event_name', 'data_to_pass_to_parent')'.
Example Child Component:
var studentComponent = Vue.component('student',{
  template:`
  <Button v-on:click="childClick1()">Child Button 1</Button>
  <Button v-on:click="childClick2()">Chilc Button 2</Button>
  `,
  methods:{
    childClick1:function(){
      this.$emit('parentClick1','naveen');
    },
    childClick2:function(){
      this.$emit('parentClick2',{name:'naveen',Id:1});
    }
  }
})
  • In the example above created a 'student' child component. It has two-button, each listening to click events. 
  • 'childClick1' event emitting an event with two parameters, the first parameter represents the event name of the parent that is going to invoked and second passing string value. 
  • 'childClick2'  also works as the first button, but data passing to the parent is an object, so to send multiple values to parent we need to use javascript object literal. 
  • Passing data to the parent component is not mandatory.
Example Parent Vue Instance:
var app = Vue({
  el:"#app",
  methods:{
    onParenClick1:function(value){
      // consol.log(value)
      // prints 'naveen'
    },
    onParentClick2:function(value){
      //console.log(value)
      // prints {name:'naveen', Id:1}
    }
  }
})
<div id="app">
  <student 
  v-on:parentClick1="onParenClick1" 
  v-on:parentClick2="onParentClick2">
  </student>
</div>
  • In example above  <student> tag  child component element. 
  • 'parentClick1', 'parentClick2' are custom events that are listening by parent Vue instance. 'onParentClick1', 'onParentClick2' call back functions for custom events on Vue instance, these get triggered when an event emitted from the child components. 
  • Custom events names on parent Vue instance must match with the event name emitted from the child component.

'v-model' Directive Or 2-way Binding:

'v-model' directive creates a 2-way binding on form input elements or components. 2-way binding works like a property from the data object assigned to the 'v-model' directive on the input element and the same property can be used in data binding on a div tag. If the value from the input element changes, on the fly the data on div tag gets changed.
Example:
var app = new Vue({
    el:"#app",
    data:{
        twoWayBidningProperty:`Hi, if any one chage me text
         box same value get reflected in where ever i binded in application`
    }
})
<div id="#app">
  <input type="text" id="egtxt" v-model="twoWayBidningProperty" />
  <div>
    {{twoWayBidningProperty}}
  </div>
</div>

Update Operation In Sample Application By Communicating  Child To Parent:

Now from our sample application on clicking edit player button, which is a child component will emit an event to the parent component with player data. On receiving data parent Vue instance will open bootstrap modal popup represents edit player. Using the Axios post method sends player data to be updated to API.
Update child component in 'app.js':
var cricketerComponent = Vue.component("circket-players", {
  props: ["players"],
  methods: {
    edit: function(value) {
      this.$emit("edit", value);
    }
  },
  template: `
  <div class="row">
        <template v-for="player in players">
          <div class="col-sm-4">
            <div class="card">
              <img src="player.jpg" class="card-img-top" />
              <div class="card-body">
                <h4 Card-title>{{player.firstName}} {{player.lastName}}</h4>
              </div>
              <ul class="list-group list-group-flush">
                <li class="list-group-item">
                  <div class="row">
                    <div class="col-sm-6">
                      Age
                    </div>
                    <div class="col-sm-6">
                      {{player.currentAge}}
                    </div>
                  </div>
                </li>
                <li class="list-group-item">
                  <div class="row">
                    <div class="col-sm-6">
                      Playing Role
                    </div>
                    <div class="col-sm-6">
                      {{player.playingRole}}
                    </div>
                  </div>
                </li>
                <li class="list-group-item">
                  <div class="row">
                    <div class="col-sm-6">
                      Batting Style
                    </div>
                    <div class="col-sm-6">
                      {{player.battingStyle}}
                    </div>
                  </div>
                </li>
                <li class="list-group-item">
                  <div class="row">
                    <div class="col-sm-6">
                      Bowling Style
                    </div>
                    <div class="col-sm-6">
                      {{player.bowlingStyle}}
                    </div>
                  </div>
                </li>
              </ul>
              <div class="card-body">
                <a href="#" class="btn btn-primary" v-on:click="edit(player)">Edit</a>
                <button class="btn btn-danger">Delete</button>
              </div>
            </div>
          </div>
        </template>
      </div>
  `
});
  • Here on the edit button registered a click event, where players data is passing as an input parameter. 
  • 'edit' function on triggered, emitting parent custom event as the first parameter and player data as the second parameter.
  •  Using '$emit()' child component communicating with parent Vue instance.
Update 'index.html':
 
<div id="app">
  <circket-players
 v-bind:players="players"
 v-on:edit="edit"
  ></circket-players>
  <div
 class="modal fade"
 id="cricketModal"
 tabindex="-1"
 role="dialog"
 aria-labelledby="exampleModalLabel"
 aria-hidden="true"
  >
 <div class="modal-dialog" role="document">
   <div class="modal-content">
  <div class="modal-header">
    <h5 class="modal-title" id="cricketModalLabel">Cricket</h5>
  </div>
  <div class="modal-body">
    <form class="justify-content-center">
   <div class="form-group row">
     <label for="txtFirstName" class="col-sm-2 col-form-label"
    >FirstName</label
     >
     <div class="col-sm-8">
    <input
      type="text"
      class="form-control"
      id="txtFirstName"
      placeholder="First Name"
      v-model="updatePlayer.firstName"
    />
     </div>
   </div>
   <div class="form-group row">
     <label for="txtLastName" class="col-sm-2 col-form-label"
    >Last Name</label
     >
     <div class="col-sm-8">
    <input
      type="text"
      class="form-control"
      id="txtLastName"
      placeholder="Last Name"
      v-model="updatePlayer.lastName"
    />
     </div>
   </div>
   <div class="form-group row">
     <label for="txtCurrentAge" class="col-sm-2 col-form-label"
    >Current Age</label
     >
     <div class="col-sm-8">
    <input
      type="text"
      class="form-control"
      id="txtCurrentAge"
      placeholder="Current Age"
      v-model="updatePlayer.currentAge"
    />
     </div>
   </div>
   <div class="form-group row">
     <label for="txtTeams" class="col-sm-2 col-form-label"
    >Major Teams</label
     >
     <div class="col-sm-8">
    <input
      type="text"
      class="form-control"
      id="txtTeams"
      placeholder="Teams"
      v-model="updatePlayer.teams"
    />
     </div>
   </div>
   <div class="form-group row">
     <label for="txtPlayingRole" class="col-sm-2 col-form-label"
    >Playing Role</label
     >
     <div class="col-sm-8">
    <input
      type="text"
      class="form-control"
      id="txtPlayingRole"
      placeholder="Playing Role"
      v-model="updatePlayer.playingRole"
    />
     </div>
   </div>
   <div class="form-group row">
     <label for="txtBattingStyle" class="col-sm-2 col-form-label"
    >Batting Style</label
     >
     <div class="col-sm-8">
    <input
      type="text"
      class="form-control"
      id="txtBattingStyle"
      placeholder="Batting Style"
      v-model="updatePlayer.battingStyle"
    />
     </div>
   </div>
   <div class="form-group row">
     <label for="txtBowlingStyle" class="col-sm-2 col-form-label"
    >Bowling Style</label
     >
     <div class="col-sm-8">
    <input
      type="text"
      class="form-control"
      id="txtBowlingStyle"
      placeholder="Bowling style"
      v-model="updatePlayer.bowlingStyle"
    />
     </div>
   </div>
   
    </form>
  </div>
  <div class="modal-footer">
    <button
   type="button"
   class="btn btn-secondary"
   data-dismiss="modal"
    >
   Cancel
    </button>
    <button type="button" class="btn btn-primary" v-on:click="saveOrUpdate">Save</button>
  </div>
   </div>
 </div>
  </div>
</div>
Bootstrap model popup used here to edit the players and on save button register with a click event to call API to save data. On <cricket-player> we can observe custom events like 'v-on:edit' which will be triggered from child component '$emit()'. 'v-model' binding used to display the data on the modal popup.
Update Vue Instance in the 'app.js':
var app = new Vue({
  el: "#app",
  data: function() {
    return {
      players: [],
      updatePlayer: {
        id: 0,
        firstName: "",
        lastName: "",
        currentAge: 0,
        teams:
          "",
        playingRole: "",
        battingStyle: "",
        bowlingStyle: ""
      }
    };
  },
  mounted: function() {
    this.getAll();
  },
  methods: {
    getAll:function(){
      axios({
        method: "get",
        url: "https://localhost:44316/api/player/all"
      }).then(response => {
        this.players = response.data;
      });
    },
    updatePlayerData:function(){
      axios({
        method:"post",
        url:"https://localhost:44316/api/player/update",
        data:{...this.updatePlayer}
      }).then(resp => {
        $("#cricketModal").modal("hide");
        this.getAll();
       
      })
    },
    edit: function(value) {
      this.updatePlayer = value;
      $("#cricketModal").modal("show");
    },
    saveOrUpdate:function(){
     if(this.updatePlayer.id > 0){
       this.updatePlayerData();
     }
    }
  }
});
  • Here 'edit' function invokes an event emitted by the child component, receives player data into it. 
  • 'updatePlayer' is a data object property in Vue instance and this property is used in a modal popup for 2-way binding. 
  • 'saverOrUpdate' function trigger on clicking save button on the modal popup, here if 'updatePlayer.id > 0' will call update API. Checking id greater than zero, because the same functionality will be used to add operation in later steps. 
  • On successfully updating again refreshing the list of data by calling get all API.
Now test the edit functionality as follows:

Create Operation:

Now we are going to do create-operation, here we will use some common code that used for the edit operation.
Update the following Html just above the child component tag as below:
<button type="button" class="btn btn-primary btn-lg" v-on:click="add()">Add Players</button>
<circket-players
  v-bind:players="players"
  v-on:edit="edit"
></circket-players>
Here add the button to create players. Button registered with the 'click' event to open the modal popup that shows an empty form to create a new player.

Update the 'app.js' as blow:
var app = new Vue({
  // note: existing code was remove for display puprpose
  methods: {
    
    savePlayerData:function(){
      axios({
        method:"post",
        url:"https://localhost:44316/api/player/save",
        data:{...this.updatePlayer}
      }).then(resp => {
        this.getAll();
        $("#cricketModal").modal("hide");
      })
    },
    
    saveOrUpdate:function(){
     if(this.updatePlayer.id > 0){
       this.updatePlayerData();
     }else{
       this.savePlayerData();
     }
    },
    add:function(){

      this.updatePlayer = {
        id: 0,
        firstName: "",
        lastName: "",
        currentAge: 0,
        teams:
          "",
        playingRole: "",
        battingStyle: "",
        bowlingStyle: ""
      }
      $("#cricketModal").modal("show");
    }
  }
});
  • Here 'add' method invoked on clicking the 'Add Players' button. 
  • In the 'add' function we are resetting the 'updatePlayer' data object property because the same property is used in editing form, which is good to clear previously edited data while creating a new one. 
  • 'updatePlayer.id == 0' represents a new player so based on id value we are implementing either creating or editing of players.
Now test the creating player in our sample application as below:

Delete Operation:

Update child component in 'app.js' as below:
var cricketerComponent = Vue.component("circket-players", {
  // Note: hiding the existing code for display purpose
  methods: {
    deletePlayer:function(id){
      this.$emit("delete",id)
    }
  },
  template: `
   <button type="button" class="btn btn-danger" v-on:click="deletePlayer(player.id)">Delete</button>
  `
});
Here 'delete' button register with 'deletePlayer' function, this function emitting the first parameter as custom event name of the parent Vue instance and the second parameter is player id to delete.
Add delete confirmation modal  in index.html as below:
<div id="app">
  <circket-players
    v-bind:players="players"
    v-on:edit="edit"
    v-on:delete="onDelete"
  ></circket-players>
  <!-- Note: hide hidded here for display purpose -->
  <div
    class="modal fade"
    id="confirmationModal"
    tabindex="-1"
    role="dialog"
    aria-labelledby="exlabel"
    aria-hidden="true"
  >
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="confirmModalLabel">Confrimation</h5>
        </div>
        <div class="modal-body">
          <h4>Are you sure you want to delete this player?</h4>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">
            Cancel
          </button>
          <button
            type="button"
            class="btn btn-primary"
            v-on:click="deletePlayerData()"
          >
            Delete
          </button>
        </div>
      </div>
    </div>
  </div>
</div>
  • Here one more bootstrap modal added for delete confirmation. 
  • 'Delete' button on confirmation modal register with click event assign with 'deletePlayerData' function which calls API to Delete. 
  • On child component, Html element parent listening to custom event name 'delete' assigned to 'onDelete' function.
Update Vue instance in 'app.js' as below:
var app = new Vue({
  // note : code was hidden for display purpose
  el: "#app",
  data: function() {
    return {
      
      idToDelete:0
    };
  },
  methods: {
    deletePlayerData:function(){
      var url = 'https://localhost:44316/api/player/delete?id=' + this.idToDelete;
      axios({
        method:"delete",
        url:url
      }).then(resp => {
        this.getAll();
        $("#confirmationModal").modal("hide");
      })
    },
    onDelete:function(id){
      this.idToDelete = id;
      $("#confirmationModal").modal("show");
    }
  }
  
});
Now test the delete operation as below:

Summary:

We have covered all the important modules to learn Vue. At the end of this article, we will get hands-on experience basic CRUD application using Vue.

Refer:

Comments

  1. I really like Vue.js and it's one of my best programming experiences to work with Vue.
    I made a restaurant management system with restaurant E-commerce with Vue + Firebase.
    It's really inspiring for me if you check my work and make a little comments.

    Restora - Restaurant Management Software with Restaurant E-commerce
    Live Demo - https://bitly.com/2PKEwrM

    ReplyDelete

Post a Comment

Popular posts from this blog

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n

.Net5 Web API Redis Cache Using StackExchange.Redis.Extensions.AspNetCore Library

In this article, we are going to explore the integration of Redis cache in .Net5 Web API application using the 'StackExchange.Redis.Exntensions' library. Note:- Microsoft has introduced an 'IDistributedCache' interface in dotnet core which supports different cache stores like In-Memory, Redis, NCache, etc. It is simple and easy to work with  'IDistributedCache', for the Redis store with limited features but if we want more features of the Redis store we can choose to use 'StackExchange.Redis.Extensions'.  Click here for Redis Cache Integration Using IDistributedCache Interface . Overview On StackExchange.Redis.Extnesions Library: The 'StackExchange.Redis.Extension' library extended from the main library 'StackExchange.Redis'. Some of the key features of this library like: Default serialization and deserialization. Easy to save and fetch complex objects. Search key. Multiple Database Access Setup Redis Docker Instance: For this sampl

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route. An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaul

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo