<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sanath Kumar on Medium]]></title>
        <description><![CDATA[Stories by Sanath Kumar on Medium]]></description>
        <link>https://medium.com/@msanathkumar?source=rss-f4512b21a90a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PVNAdCWaHsElI0ns.</url>
            <title>Stories by Sanath Kumar on Medium</title>
            <link>https://medium.com/@msanathkumar?source=rss-f4512b21a90a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 12:02:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@msanathkumar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A beginners introduction to Elastic Search]]></title>
            <link>https://medium.com/@msanathkumar/a-beginners-introduction-to-elastic-search-7ba91ac817ca?source=rss-f4512b21a90a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ba91ac817ca</guid>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[search]]></category>
            <dc:creator><![CDATA[Sanath Kumar]]></dc:creator>
            <pubDate>Wed, 25 Jul 2018 15:39:28 GMT</pubDate>
            <atom:updated>2018-07-25T15:39:28.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wrrc8xGPC1MUubb1" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">NeONBRAND</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Elastic search in its core is a document-oriented search engine. It is a document based database that lets you INSERT, DELETE , RETRIEVE and even perform analytics on the saved records. But, Elastic Search is unlike any other general purpose database you have worked with, in the past.</p><p>Elastic Search is designed specifically to solve a common but non-trivial problem in software development. No surprises here. It’s searching.</p><p>Research proves that a smart, intuitive search experience in your e-commerce store can improve the conversion rate up to a whopping 60%. But as we all know a smart search that instinctively adapts to the search keyword provided by the user is not that easy to implement. This is exactly where elastic search comes in to play.</p><p>Elastic search is essentially a search engine and offers an arsenal of features you can use to retrieve the data stored in it, as per your search criteria. And that too, at lightning speeds. Yes. It’s extremely fast.</p><h4><strong>But what makes Elastic Search so fast?</strong></h4><p>To answer this question we need to understand how the records are organized in Elastic Search. And for this let’s consider the index of a book as an analogy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NIN73D2j7KTRsv6-" /><figcaption>Photo by <a href="https://unsplash.com/@aaronburden?utm_source=medium&amp;utm_medium=referral">Aaron Burden</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To search for a word or a term we go to the index of the book, which is a list of key terms in the book, along with the page numbers where the word can be found. This is exactly how Elastic Search works.</p><p>Elastic Search is built on top of Apache Lucene, a high-performance, full-featured text search engine library written in Java. The underlying data structure used in Lucene is called an <strong>Inverted Index</strong>.</p><h4>Inverted Index</h4><p>An <strong>Inverted Index</strong> is designed for very fast full-text searches. An inverted index is a list of all the unique words that appear in any document mapped to its location in the document, where it occurs. Elastic Search takes our documents and organizes them in these inverted index data structures, exactly like the index of a book.</p><p>To search for a word or a term, Elastic Search finds the word inside the index where a list of all the words are stored along with the location of the document in which it appears. It then returns all those documents as a JSON object sorted by a relevancy score.</p><p>Elastic Search has powerful algorithms to calculate the relevancy of search results based on several different criteria, one of them being the frequency of the search term inside the indexed document.</p><h4><strong>The Document structure</strong></h4><p>The documents are stored in Elastic Search as semi-structured JSON objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*IWwpUjACkdfFwpKVaeymwA.png" /><figcaption>A sample JSON object</figcaption></figure><p>The search queries or commands to extract data back from Elastic Search also follows a JSON structure.</p><h4><strong>Understanding the terminology</strong></h4><p>The Elastic Search terminology can be a little bit confusing, especially if you are a beginner. To understand some of these terms easily,lets compare them to some of the key terms used in other databases you are familiar with.</p><ol><li><strong>Field</strong> — Take a look at the simple JSON object in the example above. It consists of 6 fields: <em>id, first_name, last_name, email, gender and ip_address</em>. A field in Elastic Search can be compared to a column in a traditional Relational Database.</li><li><strong>Document</strong> — A document is a collection of fields which can be compared to a row in a Relational Database. You might be familiar with documents, if you have prior experience in NoSQL databases like Mongo DB.</li><li><strong>Type </strong>— Each document saved in your Elastic Search index belongs to a type. A type in Elastic Search is like a table in MySQL or a collection in Mongo DB.</li><li><strong>Index </strong>— Elastic search creates indices and it’s inside these indices your documents are saved. An Elastic Search index can be visualized as a database.</li><li><strong>Mapping </strong>— Mapping is essentially a <strong>schema</strong> for the documents. A mapping in Elastic Search is a definition of how the documents are stored in an index.</li></ol><h3><strong>Installing Elastic Search</strong></h3><p>If you are a windows user you can download Elastic Search from the official website and follow the instruction given underneath the download options to install Elastic Search in your Windows PC.</p><p>Use the following commands to install Elastic Search in Ubuntu.</p><p><strong>Install the official Elastic APT package signing key</strong></p><pre>wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -</pre><p><strong>Install apt-transport https package</strong></p><pre>sudo apt-get install apt-transport-https</pre><p><strong>Adding the repository</strong></p><pre>echo &quot;deb https://artifacts.elastic.co/packages/6.x/apt stable main&quot; | sudo tee -a /etc/apt/sources.list.d/elastic.list</pre><p><strong>Installing Elastic Search</strong></p><pre>sudo apt-get update<br>sudo apt-get install -y elasticsearch</pre><p><strong>Setting the JVM heap size</strong></p><p>JVM heap size must be set to approximately half the size of your available memory. To set the JVM heap size, edit the file <em>/etc/elasticsearch/jvm.options</em> in your terminal and set Xms and Xmx values to approximately half the size of your available RAM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*qiOlH6TGn-yz-Wx6O4AgZw.png" /><figcaption>/etc/elasticsearch/jvm.options</figcaption></figure><p>Finally run the following command to start Elastic Search</p><pre>sudo service elasticsearch start </pre><p>You can check the status of the Elastic Search service using the following command.</p><pre>sudo service elasticsearch status</pre><p>Elastic Search by default run on the port<strong> 9200</strong>. Navigate to localhost:9200 in your browser and if all is well, you should see a JSON response as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*v_W7KHzyuJV5aK_i_u-ZxA.png" /><figcaption>localhost:9200</figcaption></figure><h4>Inserting a document into Elastic Search</h4><p>Fire up POSTMAN and make a post request to <em>localhost:9200</em> as follows.</p><pre>http://localhost:9200/{your_index_name}/{document_type}</pre><p>with the document as the request body as shown in the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*4LAt_MWkk7cm0_1lymYpaA.png" /><figcaption>indexing a document into the elastic search index called shop with type products</figcaption></figure><p>Elastic Search enables you to assign an <strong>id</strong> to your documents while indexing. If an <strong>id </strong>is not explicitly provided Elastic Search will assign an auto-generated <strong>id</strong>. An id can be explicitly provided on indexing your document as follows.</p><pre>POST http://localhost:9200/shop/products/001</pre><p>This will assign the <strong>id </strong>001 to the indexed record.</p><p>A <strong>GET</strong> request on localhost:9200/shop should return the following response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*X1drQiyMQXkjXZ-iCXWnZA.png" /><figcaption>GET localhost:9200/shop</figcaption></figure><p>You can see that Elastic Search has automatically created a mapping by analyzing the indexed document. You can also explicitly define a mapping to define how the documents need to be organized in Elastic Search. This allows elastic search to ignore the documents or throw an error if the supplied document does not adhere to the mapping defined.</p><p>Elastic Search is a distributed technology. Each index in Elastic Search is organized as many different shards distributed across multiple nodes. Elastic Search also allows us to define replica sets. You might notice the fields <strong>number_of_shards</strong> and <strong>number_of_replica_sets</strong> in the JSON response above.</p><p>This is an indication of the underlying structure of Elastic Search. Replica-sets ensure data security even if a node goes down temporarily.</p><h4>Searching for a document</h4><p>A simple match query for searching indexed documents from Elastic Search will be as shown in the snippet below.</p><pre>POST <a href="http://localhost:9200/shop/products/_search">http://localhost:9200/shop/products/_search</a></pre><pre>{<br>    &quot;query&quot;: {<br>        &quot;match&quot; : {<br>            &quot;name&quot; : &quot;product name&quot;<br>         }<br>     }<br>}</pre><p>Let’s see how the above search query can be modified to math multiple fields.</p><pre>POST <a href="http://localhost:9200/shop/products/_search">http://localhost:9200/shop/products/_search</a></pre><pre>{<br>  &quot;query&quot;: {<br>      &quot;multi_match&quot; : {<br>          &quot;query&quot; : &quot;search_keyword&quot;,<br>          &quot;fields&quot;: [&quot;name&quot;, &quot;product_code&quot;]<br>      }<br>   }<br>}</pre><p>Elastic Search allows us to write powerful queries and aggregations to retrieve saved documents from the elastic index. In the next installment of this article, we will install <strong>Kibana</strong>, a data visualizer for Elastic Search and dive in-depth into powerful Elastic Search queries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ba91ac817ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Vuex — Zero to Hero]]></title>
            <link>https://medium.com/dailyjs/mastering-vuex-zero-to-hero-e0ca1f421d45?source=rss-f4512b21a90a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0ca1f421d45</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuex]]></category>
            <dc:creator><![CDATA[Sanath Kumar]]></dc:creator>
            <pubDate>Sun, 22 Jul 2018 16:55:18 GMT</pubDate>
            <atom:updated>2018-07-26T14:14:27.577Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0QaKNqJ3A465rLrnGGMgA.jpeg" /><figcaption>Original photo by <a href="https://unsplash.com/photos/OVbeSXRk_9E?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nikita Kachanovsky</a> on <a href="https://unsplash.com/search/photos/computer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4877k4Hq9dPdtmvg9hnGFA.jpeg" /></figure><p>The official documentation of Vuex defines it as a <strong>state management pattern</strong> + library for Vue.js applications. <em>But what does this mean? What is a state management pattern?</em></p><p>Imagine working on a large web app with hundreds of routes and components. Wouldn&#39;t it be easier if we could store all the data we ever need inside the app, in one centralized storage location?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*HWBipJ4YFcEGrBoJA3jhuQ.jpeg" /></figure><p>Every component or route inside our application will request data from the Vuex state and commits modified data back to the state.</p><p>In essence, the Vuex state can be viewed as a single source of truth for the entire application.</p><p>Data is stored inside the state as a single JSON object. For example :</p><pre>state : {<br>    name : “John Doe”,<br>    age : “28”,<br>}</pre><p>But how can our components and routes access the data stored in our state? We define <strong>Getters</strong> inside our Vuex store which returns the data from our store back to our components. Let’s see how a simple <strong>Getter</strong>, to retrieve the name stored in our state looks like.</p><pre>getters : {<br>  NAME : state =&gt; {<br>    return state.name<br>  }<br>}</pre><p>Notice that, we have capitalized the name of the getter. This is just a recommended coding convention and it’s not absolutely necessary for you to follow the same if you are not a fan of it.</p><p>Now that we have defined a getter for the name, it’s incredibly easy to fetch the value of name inside our component, as shown in the snippet below.</p><pre>let name = this.$store.getters.NAME</pre><p>We have figured out how to <strong>get</strong> data from the state, let’s see how we can <strong>set</strong> data into our state. We define setters, right? Except, Vuex setters are named slightly different. We define <strong>a Mutation</strong> to set data into our Vuex state.</p><pre>mutations : {<br>  SET_NAME : (state,payload) =&gt; {<br>    state.name = payload,<br>  }<br>}</pre><p>What the heck is a payload? A <strong>payload</strong> is simply the data passed to our mutation from the component committing the mutation. How do we do that ? Simple…</p><pre>this.$store.commit(“SET_NAME”,your_name)</pre><p>This snippet of code will mutate the state and set whatever value that is assigned to your_name, to the name property inside our Vuex state.</p><blockquote>Mutations are synchronous</blockquote><p>Imagine we have a list of names, stored in a database on a remote server. The server provides us an API endpoint that returns an array of names, which can be consumed in our Vue.js application. Of course, we can use <strong>Axios </strong>to make a get request to the API endpoint and retrieve the data.</p><pre>let { data } = await Axios.get(‘https://myapiendpoint.com/api/names&#39;)</pre><p>We could then commit the returned array in to our Vuex store via mutation. Simple.. right? Well, not so much. Mutations are synchronous and we cannot run asynchronous operations such as API calls inside a mutation.</p><p>So what do we do now. ? We create <strong>Actions.</strong></p><p>Actions are similar to mutation, but instead of mutating the state directly they commit a mutation. Confused? Let’s inspect an action declaration.</p><pre>actions : {<br>  SET_NAME : (context,payload){<br>     context.commit(&quot;SET_NAME&quot;,payload);<br>  }<br>}</pre><p>We have defined an action called SET_NAME which accepts context and payload as parameters. The action commits the mutation SET_NAME created earlier with the payload passed to it, that is <strong>your_name</strong>.</p><p>Now instead of committing the mutation directly, our components dispatch an action SET_NAME, with the new name as payload as follows:</p><pre>this.$store.dispatch(&quot;SET_NAME&quot;,your_name)</pre><p>The action then commits the mutation with the payload passed to it, that is your_name.</p><h4>But why ?</h4><p>You might be wondering why an action declaration is required when we could simply commit our mutations with the new value directly from our components. As mentioned above mutations are synchronous but actions are not.</p><p>In the above example, consider a case when you have to update the value of name, not just in your state but also on a database running on a remote server. I am pretty sure this is how you are going to use Vuex in a real project 99% of the time. Take a look at the following code snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa013303ef5f04c9b89a99aae90b87cd/href">https://medium.com/media/fa013303ef5f04c9b89a99aae90b87cd/href</a></iframe><p>The code itself is self-explanatory. We use Axios to post the name to an API end-point. If the POST request is successful that is the value of the field name has been successfully changed in the server, we commit the SET_ NAME mutation to update the value of name inside our state as well.</p><blockquote>Make it a practice to never commit your Mutations directly. Always use Actions to commit your mutations</blockquote><h4>Setting up a Vuex store in Vue.JS</h4><p>Let’s dive in deeper and learn how we can actually implement Vuex in a real application.</p><p><strong>Setp 1. Install Vuex</strong></p><pre>npm install --save vuex</pre><p><strong>Step 2. Creating a Vuex Store</strong></p><ol><li>Create a folder named <strong>store</strong> inside your root directory.</li><li>Create an <strong>index.js</strong> file inside the newly added store folder and use the snippet below to create a new store.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e58a21ee6eb9071ce9f324c92ee8ee0d/href">https://medium.com/media/e58a21ee6eb9071ce9f324c92ee8ee0d/href</a></iframe><p><strong>Step 3. Add Vuex store to our Vue.Js application</strong></p><ol><li>Import the <strong>store</strong> inside main.js file.</li></ol><pre>import { store } from &#39;./store&#39;</pre><p>2. Attach the <strong>store</strong> to our Vue instance as shown below.</p><pre>new Vue({<br>  el: &#39;#app&#39;,<br> <strong> <em>store</em></strong>,<br>  router,<br>  render: h =&gt; h(App)<br>})</pre><p>And we are done. Now we can add <strong>state variables</strong>, <strong>getters</strong>, <strong>mutations</strong> and <strong>actions</strong> inside our Vuex store.</p><h4><strong>An Example</strong></h4><p>Take a look at the Vuex store of a simple to-do list application. “Not another TODO list !!” Right? Well, don’t worry. By the end of this article, you will be well equipped to use Vuex in all its might and glory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/298d255e8d936d88ce64fbdcc2acd30a/href">https://medium.com/media/298d255e8d936d88ce64fbdcc2acd30a/href</a></iframe><h4>Adding a new item to the to-do list</h4><p>Inside your component, dispatch an action <strong>SAVE_TODO</strong> with the to-do item as payload as shown in the code snippet below.</p><pre>let item = &quot;Get groceries&quot;<br>this.$store.dispatch(&#39;SAVE_TODO&#39;,item)</pre><p>The action <strong>SAVE_TODO </strong>makes a POST request to your API end-point and then commits a <strong>mutation ADD_TODO</strong>, which pushes the to-do list item to the state variable <strong>todos</strong>.</p><h4>Fetching your to-do list</h4><p>Inside the <strong>mounted()</strong> block in your component, dispatch the second action <strong>GET_TODO</strong>, which fetches all the to-do items from your API end-point and saves it to the state variable todos, by committing a mutation SET_TODO</p><pre>mounted(){<br>    this.$store.dispatch(&#39;GET_TODO&#39;)<br>}</pre><h4>Accessing the to-do list inside your component</h4><p>Create a computed property as shown in the snippet below, to access the todos item inside your component.</p><pre>computed : {<br>  todoList(){<br>     return this.$store.getters.TODOS<br>  }<br>}</pre><p>Inside your component you can access the computed property as shown below.</p><pre>&lt;div class=&quot;todo-item&quot; v-for=&quot;item in todoList&quot;&gt;&lt;/div&gt;</pre><h4>Using Map Getters method</h4><p>There is an even simpler way of accessing your todos list inside you component using the mapGetters method provided by Vuex.</p><pre>import {mapGetters} from &#39;vuex</pre><pre>computed : {<br>...mapGetters([&#39;TODOS&#39;]),<br>  //Other computed properties<br>}</pre><p>You might have already guessed this, but the code inside your template definition have to modified as shown in the snippet below.</p><pre>&lt;div class=&quot;todo-item&quot; v-for=&quot;item in TODOS&quot;&gt;&lt;/div&gt;</pre><p>Notice how we have used the ES6 spread operator [ <strong>… </strong>] inside our computed properties.</p><blockquote>A Vuex store is not just a single source of truth in your application, it is also designed to be that single point which should alter this truth.</blockquote><p>This needs a little bit of explanation. We already learned to define Actions to <strong>get</strong> and <strong>set</strong> the todos item in our state. What if we had to update the item and mark it complete ? Where do we run the code for this ?</p><p>You might find contrasting opinions on the subject all over the Internet, and there is no clear guidelines specified in the documentation as well.</p><p>I would recommend keeping all your API calls inside <strong>Actions</strong> in your Vuex store. This way every change that gets committed to your state only comes from inside the store and makes it easier for you to debug and make the code easier to understand. It also has the added benefit of making edits in your code easier.</p><p>Now, how do we delete and update an item from the todos list ? Try implementing an action and mutation to update and remove items from your todos list and let me know in the comments below.</p><h4>Organizing your code</h4><p>Saving all your state variables, getters, actions, and mutations in one single file will quickly become cumbersome once you start working on medium to large sized real-world applications. Let’s see how we can organize our store into multiple files as modules.</p><p>Create a new folder inside your store called modules. Add a new file called <strong>todos.js</strong> inside the modules folder.</p><pre>const state = {}<br>const getters = {}<br>const mutations = {}<br>const actions = {}</pre><pre>export default{<br>    state,getters,mutations,actions<br>} </pre><p>Now you can move your state variables, getters, mutations and actions from <strong>index.js</strong> into <strong>todos.js</strong> file. Don’t forget to import <strong>Axios</strong>. All we need to do now is let Vuex know we have created a store module and where to find it. Your new index.js file should look something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f312b811bbe136b14175c1819e70df0/href">https://medium.com/media/9f312b811bbe136b14175c1819e70df0/href</a></iframe><p>And your <strong>todos.js</strong> file will be as shown in the gist below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77bfa6303bf16127084dda39008903ec/href">https://medium.com/media/77bfa6303bf16127084dda39008903ec/href</a></iframe><h4>Important Takeaways</h4><ol><li>The state of your app is stored as a single large JSON object.</li><li><strong>Getters</strong> are used to access values stored in your state.</li><li><strong>Mutations</strong> update your state. It is to be remembered that mutations are synchronous.</li><li>All asynchronous operations must be executed inside <strong>Actions</strong>. Actions alter the state by committing a mutation.</li><li>Make it a practice to always commit a <strong>Mutation</strong> only through an <strong>Action</strong>.</li><li><strong>Modules</strong> can be used to organize your store into multiple smaller store files.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4877k4Hq9dPdtmvg9hnGFA.jpeg" /></figure><p>Vuex makes working with Vue so much easier and fun. If you are a beginner there might be instances where it’s tough for you to decide if you need to use Vuex or not in certain areas of your application. Follow your gut. You will be up-to-speed pretty quick.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0ca1f421d45" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dailyjs/mastering-vuex-zero-to-hero-e0ca1f421d45">Mastering Vuex — Zero to Hero</a> was originally published in <a href="https://medium.com/dailyjs">DailyJS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a simple real-time chat application using Socket.io, Express and Vue JS]]></title>
            <link>https://medium.com/@msanathkumar/building-a-simple-real-time-chat-application-using-socket-io-express-and-vue-js-d263c08a4c59?source=rss-f4512b21a90a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d263c08a4c59</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[vuex]]></category>
            <category><![CDATA[socketio]]></category>
            <dc:creator><![CDATA[Sanath Kumar]]></dc:creator>
            <pubDate>Thu, 19 Jul 2018 16:45:03 GMT</pubDate>
            <atom:updated>2018-08-05T08:24:27.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3MRzTCI7AzYqq_1hd7sf3A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@stanleydai?utm_source=medium&amp;utm_medium=referral">Stanley Dai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Vue JS is awesome. Add <strong>socket.io</strong> to the mix and building powerful real-time Apps feels like a breeze. In this article let’s see how we can build a real-time group chat application using <strong>Express</strong>,<strong> Socket.io</strong> and <strong>Vue JS</strong>.</p><p>I will be providing complete codes at the end of this article which can be downloaded to your local development setup.</p><p>Let’s start by creating an Express server. Inside your project directory create a new project using the commands below.</p><pre>mkdir socket-server<br>cd socket-server<br>npm init -y</pre><h4><strong>Installing Express</strong></h4><p>Install express inside our NodeJS app using the following command.</p><pre>npm install -- save express</pre><p>Create an <strong>index.js</strong> file inside your project directory and add the following code inside to get your express server up and running.</p><pre>const express = require(‘express’);<br>const app = new express();</pre><pre>app.listen(5000,() =&gt; {<br>    console.log(“Howdy, I am running at PORT 5000”);<br>})</pre><h4><strong>Installing Nodemon</strong></h4><p>Installing nodemon will ensure that you don’t have to restart your server every time you make changes to your codes. Let’s install nodemon as a development dependency using the following command.</p><pre>npm install -- save-dev nodemon</pre><p>Now inside your <strong><em>package.json</em></strong> file add the following line inside the<strong><em> scripts </em></strong>section<strong><em>.</em></strong></p><pre>&quot;dev&quot; : &quot;nodemon index.js&quot;</pre><p>Finally, use the following command to run your server</p><pre>npm run dev</pre><p>We need a few other npm packages as well for our server app. They are <strong>socket.io</strong>, <strong>mongoose</strong>, <strong>body-parser</strong> and <strong>cors. </strong>Let’s install them using the following command.</p><pre>npm install -- save socket.io body-parser mongoose cors</pre><h3><strong>Let’s code</strong></h3><p>Create two folders named <strong>config</strong> and <strong>model </strong>inside your root directory. Create a new file <strong><em>keys.js</em></strong> inside the <strong>config</strong> folder and paste your Mongo DB url inside it as shown in the snippet below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b691aa809c6778f92536e1b0b445513/href">https://medium.com/media/4b691aa809c6778f92536e1b0b445513/href</a></iframe><h3><strong>Coding the Server</strong></h3><p>Create a new file named <strong>index.js</strong> inside your root directory and paste the following code inside it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9a17fd27d7c14c2783219a2543e4e07/href">https://medium.com/media/a9a17fd27d7c14c2783219a2543e4e07/href</a></iframe><p>We have created a new <strong>socket.io</strong> instance attached to our express server, which listens to incoming messages. Every time a new <strong><em>chat </em></strong>is emitted by our Vue JS client the incoming message is saved to Mongo DB.</p><p>We have also written a <strong><em>chat API </em></strong>that returns all the saved chats in our<strong><em> chat </em></strong>collection. we are also using the <strong>cors</strong> package to enable all cors requests.</p><p>This is how the mongoose schema for our <strong><em>chat</em></strong> collection looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e495b912b7d44962f5723ff56df9d3d5/href">https://medium.com/media/e495b912b7d44962f5723ff56df9d3d5/href</a></iframe><p>Paste the above snippet inside <strong>model</strong> → <strong>message.js</strong>, and this pretty much sums up our server side code. Pretty simple right ?</p><p>Fire up your Express server using <strong>npm run dev.</strong> Now, we have the Express Server running at <strong>http://localhost:5000 </strong>with our <strong>socket.io</strong> instance listening to incoming connections and messages.</p><h3><strong>Coding the Client</strong></h3><p>Now let’s start building our front-end application. I bet it’s going to be fun as this is where all the real action happens.</p><p>Assuming you have Vue CLI installed in your computer, create a new Vue project inside your project directory with the following command.</p><pre>vue init webpack-simple socket-client<br>cd socket-client<br>npm install</pre><blockquote>If you don’t have Vue installed in your development setup you can always install it using the npm package manager as follows</blockquote><pre>npm install -g vue-cli</pre><h4><strong>Adding Vuetify</strong></h4><p><strong>Vuetify</strong> is an elegant components framework developed for Vue JS. We will be using <strong>Vuetify</strong> to design the front-end of our application. In case you haven&#39;t used vuetify in the past don’t worry. You will have a pretty good understanding of how it works by the end of this article.</p><h4><strong>Let’s install vuetify</strong></h4><pre>npm install -- save vuetify</pre><p>Now, inside your main.js file add the following snippet to add Vuetify to your project.</p><pre>import Vuetify from ‘vuetify’<br>Vue.use(Vuetify)<br>import ‘vuetify/dist/vuetify.min.css’</pre><p>Now let’s add <strong>vuex</strong>, <strong>axios</strong>, <strong>moment</strong> and <strong>socket.io </strong>to our project</p><pre>npm install — save vuex axios vue-moment vue-socket-io</pre><p>We will use Axios to fetch the messages from the <strong>Chat API</strong> we have implemented. Also, we will be using moment to prettify the timestamps of each of our messages.</p><p>We will also be using the Vuex state extensively. If you are not familiar with Vuex, I would recommend reading my article on Mastering Vuex.</p><p><a href="https://medium.com/@msanathkumar/mastering-vuex-zero-to-hero-e0ca1f421d45">Mastering Vuex — Zero to Hero</a></p><h4><strong>Setting up socket.io in Vue JS</strong></h4><p>Add the following snippet inside your <strong><em>main.js</em></strong> file to set up <strong><em>socket.io</em></strong> inside the Vue App</p><pre>import VueSocketio from ‘vue-socket.io’<br>Vue.use(VueSocketio, ‘<a href="http://13.232.93.184:5000&#39;">http://localhost:5000&#39;</a>)</pre><h4><strong>Setting up Vuex store</strong></h4><p>Create a new folder <strong><em>store </em></strong>inside your root directory and add a new <strong>index.js</strong> file inside it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4010acfe271c389629e1a7db7731bd5/href">https://medium.com/media/c4010acfe271c389629e1a7db7731bd5/href</a></iframe><p>Create an empty store as shown in the snippet and add two items to the state</p><ol><li>chats</li><li>handle</li></ol><pre>state : {<br>  chats : null,<br>  handle : “”<br>},</pre><p>Import the store inside the <strong>main.js</strong> file and attach it to your Vue instance as follows.</p><pre>import { store } from ‘./store’</pre><pre>new Vue({<br> el: ‘#app’,<br> store,<br> render: h =&gt; h(App)<br>})</pre><p>Notice how we have used ES6 to write just <strong>store </strong>rather than<strong> </strong><em>store : store</em>.</p><p>This is how the final <strong>main.js</strong> file looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/add0f2c6e5ce3b26900933219e08205b/href">https://medium.com/media/add0f2c6e5ce3b26900933219e08205b/href</a></iframe><p>Now that all the boilerplate is out of our way let’s get our hands dirty and start building our app.</p><h4><strong>Basic overview of the App</strong></h4><p>Before we begin, I’ll give you a basic overview of the app we are developing. For the purpose of keeping this article as simple as possible we will not be adding any kind of authentication for the users of our app. Instead, each user will be uniquely identified by a handle of the users choice.</p><p>However, this design could be easily extended to support user authentication with minor changes to the code.</p><p>As a user loads our application, he/she will be asked to save a handle which will then be stored in our Vuex store. Once, a user logs in with the handle of his choice he can simply type in messages and hit ENTER to emit the chat to the server which will be saved in our collection and the server in return will emit the same message back to the client which will be intercepted by the socket listener on the client.</p><p>Confused ? Don’t worry. Once we start coding our components you will get the hang of it.</p><h4><strong>The components</strong></h4><p>We will have 3 components inside our App.</p><ol><li>The Chat Box</li><li>The Chat Items</li><li>And, The Handle Input</li></ol><p>Let’s create those components now.</p><p>Create a new folder <strong>components</strong> inside the root directory of your project and add 3 files inside named <strong>ChatBox.vue</strong>, <strong>ChatItem.vue</strong> and <strong>Handle.vue</strong></p><h4><strong>Handle.vue</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*vcvE4wkp_yudosuXAQoFTg.png" /><figcaption>The Handle Component</figcaption></figure><p>This component prompts the user to input a handle and save the handle inside our Vuex store. Paste the following code inside the <strong>handle.vue</strong> file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3ffa576d01a422eaaef5d036ab95e36/href">https://medium.com/media/a3ffa576d01a422eaaef5d036ab95e36/href</a></iframe><p>We have a card-view inside of which there is a Text Field and a Button. Upon clicking the button we are dispatching an action <strong>SET_HANDLE</strong> with the handle as payload, to save the user-input to our Vuex store.</p><p>Inside actions in our store create a new action SET_HANDLE as follows.</p><pre>SET_HANDLE : (context,payload)=&gt; {<br>  context.commit(“SET_HANDLE”,payload);<br>}</pre><p>Now, create a new mutation SET_HANDLE inside mutations to save the handle to the state.</p><pre>SET_HANDLE : (state,payload) =&gt; {<br>    state.handle = payload;<br>}</pre><blockquote>In case you are new to Vuex make it a practice to always use actions to commit a mutation even if no asynchronous operations are involved.</blockquote><p>Now that we have saved the user handle to our state let’s code our chat box to emit the messages sent by our users to the server.</p><p>Inside <strong>ChatBox.vue</strong> add the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e336b395eb79bf5b1b984b6da0c0e9e/href">https://medium.com/media/5e336b395eb79bf5b1b984b6da0c0e9e/href</a></iframe><p>Let’s inspect whats going on in the code. We have a form with a text-field inside. Upon submission <strong>sendMessage()</strong> method is triggered, which emits the message to our server via sockets as follows:</p><pre>let response = await this.$socket.emit(‘chat’,message);</pre><p>Now, if you remember, we have setup a custom listener called chat in our socket.io instance inside our Express server in the last section. The express server intercepts our message saves it to the Database and emits the message back with a custom <strong>chat</strong> event back to the client.</p><p>Let’s get back to our <strong>App.vue</strong> file now and display the chat messages. We will also setup a custom listener to listen to chats emitted by the server.</p><p>This is how the completed code of our <strong>App.vue</strong> file looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ab2d1350a4572e69e8b81333b156e35/href">https://medium.com/media/5ab2d1350a4572e69e8b81333b156e35/href</a></iframe><p>In the code above, you can see that we have imported the three components we have created. Also, we have couple of getters CHATS, and HANDLE. You’ll see how they are defined in a minute.</p><p>In the mounted block we are dispatching an action SET_CHAT which fetches all the existing chats from the the API we have created in our express server and saves the chat to the state via mutation.</p><p>There is also a socket block which wraps all the codes connected to the <strong>socket.io</strong> client. The chat method listens to incoming emits from the server and dispatches an action ADD_CHAT which pushes the received message to the chat array in our state.</p><p>Let’s see how the complete <strong>store</strong> file looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cbe00ef1dbdafa1c49d1f03d0a00593/href">https://medium.com/media/3cbe00ef1dbdafa1c49d1f03d0a00593/href</a></iframe><h4><strong>The User Interface</strong></h4><p>As the user loads the App handle is <em>null</em> in the state. Messages are displayed only if handle is <em>not null</em> and the handle component is displayed in the else block as shown in the code.</p><p>Once the user inputs a handle the Handle component is replaced by the messages block which loops thorough the messages and renders the third component <strong>ChatItem </strong>with the message as props<strong>.</strong></p><p>Let’s see how the <strong>ChatItem</strong> component looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d43b0a01f3a9902d5225cf895cb2cc0/href">https://medium.com/media/3d43b0a01f3a9902d5225cf895cb2cc0/href</a></iframe><p>The <strong>ChatItem</strong> component has an <strong>isMyhandle</strong> method to differentiate incoming and outgoing chats and sets the color of the handle accordingly. Also, Vue moment is used to prettify the date which is displayed as a tool-tip on hover.</p><p>My original plan was to add a bonus section at the end of the article, with tips on how to extend the group chat application we developed in to a real time one-to-one chat app. But, I would rather publish it in a different article as this one’s already too long.</p><p>Find complete codes for the server and client below.</p><ul><li><a href="https://github.com/sanath-kumar/socket-server">sanath-kumar/socket-server</a></li><li><a href="https://github.com/sanath-kumar/socket-client">sanath-kumar/socket-client</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d263c08a4c59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Transitions and Animations in VueJS]]></title>
            <link>https://medium.com/@msanathkumar/understanding-transitions-and-animations-in-vuejs-115a0f5c6fbc?source=rss-f4512b21a90a------2</link>
            <guid isPermaLink="false">https://medium.com/p/115a0f5c6fbc</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Sanath Kumar]]></dc:creator>
            <pubDate>Thu, 26 Apr 2018 15:00:04 GMT</pubDate>
            <atom:updated>2018-04-26T15:00:04.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zJ4sw6mW391Y7d5-UcIIQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/feXpdV001o4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Anas Alshanti</a> on <a href="https://unsplash.com/search/photos/programming?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Animations not only makes our applications pretty, it is also a great UX tool that can make the interface of our App intuitive and easier for the users to get around. VueJS offers multiple ways to apply animations and transitions to spice up the User Experience of our Web Apps. VueJS has a built-in transition component, inside of which we wrap the elements that must be animated.</p><pre>&lt;transition name=&quot;fade&quot;&gt;<br>    &lt;p&gt;Animate Me&lt;/p&gt;<br>&lt;/transition&gt;</pre><h3>Using Transitions</h3><p>VueJS automatically adds four classes to an element wrapped inside the transition component. These classes are:</p><ol><li>v-enter</li><li>v-enter-active</li><li>v-leave</li><li>v-leave-active</li></ol><p>These are the four standard classes provided by VueJS for transitions. Now, how do we override these standard classes with our own? Turns out, it’s as easy as adding a name property to the transition component. VueJS automatically prefixes the name of the transition component to each of these classes and in effect, the four default classes are replaced by <strong><em>*-enter</em></strong><em>,</em><strong><em> *-enter-active</em></strong><em>, </em><strong><em>*-leave</em> </strong>and <strong><em>*-leave-active </em></strong>where <strong><em>* </em></strong>is the name of the transition.</p><p>Now let’s animate a block on our page using transitions. In the <strong><em>App.vue</em></strong> file create a template as shown in the code block below:</p><pre>&lt;template&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;div class=&quot;col-md-6 col-md-offset-3&quot;&gt;<br>            &lt;button <br>             class=&quot;btn btn-primary&quot; <br>             @click=&quot;show = !show&quot;&gt;<br>                 Show<br>            &lt;/button&gt;<br>        &lt;/div&gt;<br>        &lt;br&gt;&lt;br&gt;<br>        &lt;transition name=&quot;fade&quot;&gt;<br>            &lt;div class=&quot;alert alert-info&quot; v-if=&quot;show&quot;&gt;<br>                Howdy! How cool is VueJS ?<br>            &lt;/div&gt;<br>        &lt;/transition&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>    export default {<br>        data(){<br>            return { show : false }<br>        }<br>    }<br>&lt;/script&gt;</pre><pre>&lt;style&gt;<br>    .fade-enter{<br>        opacity: 0;<br>    }<br>    .fade-enter-active{<br>        transition: opacity 1s;<br>    }<br>    .fade-leave{<br>        /* opacity: 1; */<br>    }<br>    .fade-leave-active{<br>        transition: opacity 1s;<br>        opacity: 0;<br>    }<br>&lt;/style&gt; </pre><blockquote>I have included bootstrap via CDN inside <strong>index.html</strong> file to get some additional helper classes.</blockquote><p>As you can see, we have named the transition <strong><em>fade. </em></strong>VueJS automatically adds four classes — <strong><em>fade-enter</em></strong><em>, </em><strong><em>fade-enter-active</em></strong><em>, </em><strong><em>fade-leave</em></strong>, and <strong><em>fade-leave-active</em></strong> for us to define our animations.</p><p>The <strong><em>fade-enter</em></strong> animation is added to the element for exactly one frame before the element is loaded into the DOM. So we set the opacity of the animation to <strong>0</strong> to keep the alert hidden, as the DOM is rendered. The <strong><em>fade-enter-active</em></strong> class is added to the element throughout the duration of the animation which in our case is set to 1s. The <strong><em>fade-leave</em></strong> and <strong><em>fade-leave-active</em></strong> work in the same fashion too and is pretty much what the name represents.</p><blockquote>We do not have to explicitly set the opacity to 1 inside fade-leave class, as already the default value for opacity at this point is 1. This is exactly why the opacity is not explicitly set to 1 at the end of fade-enter-active as well.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*Ua3RVcK-K6j86EZ4UlgYgQ.gif" /></figure><p>VueJS automatically detects <strong>v-if</strong> attached to an element wrapped inside a transition component. In the above code snippet, the alert is shown if <strong><em>show </em></strong>is set to true, and the on-click event for the button toggles the value of <strong><em>show.</em></strong></p><blockquote>An important point to be noted here is that VueJS can only Animate one element inside a transition. Rather, only one element inside the transition can be attached to the DOM at any given instance.</blockquote><p>For instance, the following transition will not work as expected in VueJS</p><pre>&lt;transition name=&quot;fade&quot;&gt;<br>    &lt;div class=&quot;alert alert-info&quot; v-if=&quot;show&quot; key=&quot;info&quot;&gt;<br>        Howdy! How cool is VueJS ?<br>    &lt;/div&gt;<br>    &lt;div class=&quot;alert alert-warning&quot; v-if=&quot;show&quot; key=&quot;warning&quot;&gt;<br>        VueJS is Awesome!!<br>    &lt;/div&gt;<br>&lt;/transition&gt;</pre><p>In the above code snippet, both the elements enclosed inside the transition will be attached to the DOM, as both of them satisfies the condition show == true at the same time. But, what if we replace <strong><em>v-if</em></strong> with <strong><em>v-else</em></strong> ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*c80oNf2M8oqfSa42bTPUIw.gif" /></figure><p>Now, as only one element is attached to the DOM at any given instant, the transition works perfectly. Sleek, right? It must also be noticed that VueJS requires each element to be identified by a unique <strong><em>key </em></strong>for the animations to work properly, in-case you have more than one element enclosed inside a transition.</p><p>Now, you might be wondering why your animation is not smooth as in the gif above. Normally, VueJS does not wait for the first element to be removed from the DOM completely before attaching the second element to the DOM. So, you might experience a jump in your animation.</p><p>How do we solve this? Turns our VueJS got it covered.</p><h3>Transition Modes</h3><p>VueJS offers two transition modes to fix the problem mentioned above. They are <strong>out-in</strong> and <strong>in-out.</strong></p><pre>&lt;transition name=&quot;fade&quot; mode=&quot;out-in&quot;&gt;<br>    &lt;div class=&quot;alert alert-info&quot; v-if=&quot;show&quot; key=&quot;info&quot;&gt;<br>        Howdy! How cool is VueJS ?<br>    &lt;/div&gt;<br>    &lt;div class=&quot;alert alert-warning&quot; v-else key=&quot;warning&quot;&gt;<br>        VueJS is Awesome!!<br>    &lt;/div&gt;<br>&lt;/transition&gt;</pre><p>Setting the mode as <strong>out-in</strong> will allow a smooth transition from one element to the other, as the second element will be attached to the DOM only after the first one is removed.</p><h3>Setting up an on-load animation</h3><p>Now, in the above example, the second alert shows up as soon as the page loads up. But you might notice, the animation doesn’t work. How do we animate an element, the first time it is attached to the DOM ? Just add <strong><em>appear</em> </strong>to the transition component and you are done. How easy! Right ?</p><pre>&lt;transition name=&quot;fade&quot; mode=&quot;out-in&quot; appear&gt;<br>    &lt;div class=&quot;alert alert-info&quot; v-if=&quot;show&quot; key=&quot;info&quot;&gt;<br>        Howdy! How cool is VueJS ?<br>    &lt;/div&gt;<br>    &lt;div class=&quot;alert alert-warning&quot; v-else key=&quot;warning&quot;&gt;<br>        VueJS is Awesome!!<br>    &lt;/div&gt;<br>&lt;/transition&gt;</pre><h3>Using CSS Animations</h3><p>CSS animations can be used the same way transitions are used in VueJS. Let’s try using <strong><em>animate.css </em></strong>with our VueJS app.</p><p>You can either use <strong>npm </strong>or a CDN to add animate.css to your VueJS app.</p><pre>npm install animate.css --save</pre><p>Let’s import <strong>animate.css</strong> to the <strong>index.html</strong> file using a CDN</p><pre>&lt;link rel=&quot;stylesheet&quot;<br>  href=&quot;https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css&quot;&gt;</pre><p>Animate.css offers us CSS classes to easily add animations to our elements. But how do we make VueJS apply these classes to our elements? VueJS accepts <strong><em>enter-class, enter-active-class, leave-class</em></strong> and <strong><em>leave-active-class</em></strong> as inputs to help us attach the animation classes to our elements. In most cases, the <strong>enter-active-class</strong> and <strong>leave-active-class</strong> are enough to get the desired animations.</p><pre>&lt;transition mode=&quot;out-in&quot;<br>appear<br>enter-active-class=&quot;animated bounceIn&quot;<br>leave-active-class=&quot;animated bounceOut&quot; &gt;<br>     &lt;div class=&quot;alert alert-info&quot; v-if=&quot;show&quot; key=&quot;info&quot;&gt;<br>         Howdy! How cool is VueJS ?<br>     &lt;/div&gt;<br>     &lt;div class=&quot;alert alert-warning&quot; v-else=&quot;&quot; key=&quot;warning&quot;&gt;<br>         VueJS is Awesome!!<br>     &lt;/div&gt;<br>&lt;/transition&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*cNCCB7kR3r2v50-t_skPYA.gif" /></figure><p>We can also control the duration of the animation. Just bind a directive <strong><em>duration </em></strong>to the transition component and set the desired duration as shown below</p><pre>&lt;transition mode=&quot;out-in&quot;<br>appear<br>enter-active-class=&quot;animated bounceIn&quot;<br>leave-active-class=&quot;animated bounceOut&quot; <br>:duration=&quot;500&quot;&gt;<br>     &lt;div class=&quot;alert alert-info&quot; v-if=&quot;show&quot; key=&quot;info&quot;&gt;<br>         Howdy! How cool is VueJS ?<br>     &lt;/div&gt;<br>     &lt;div class=&quot;alert alert-warning&quot; v-else=&quot;&quot; key=&quot;warning&quot;&gt;<br>         VueJS is Awesome!!<br>     &lt;/div&gt;<br>&lt;/transition&gt;</pre><h3>Transition JavaScript Hooks</h3><p>So far we have used CSS to animate our elements. We can also use JavaScript to influence the style, position and much more of our elements. The transition elements that VueJS ships with emits some events at certain points in time. And we can listen to these events to execute our JavaScript code. We can see a similar pattern here as with the CSS classes we dealt with earlier.</p><p>Upon adding our element to the DOM, we have the <strong><em>before-enter </em></strong>hook, similar to the <strong><em>enter</em></strong> CSS class that is attached for a single frame. Then there is the <strong><em>enter</em></strong> hook where we typically play our animation. Then we have the <strong><em>after-enter </em></strong>which is executed when the animation is finished. Finally, we have the <strong><em>enter-canceled</em></strong> hook which is called whenever the condition that would add the element is changed before the animation is finished.</p><p>Similarly, we have — <strong><em>before-leave,leave, after-leave </em></strong>and<strong><em> leave-canceled</em></strong> hooks, for leaving. It is perfectly fine to use these JavaScript hooks alongside CSS animations to execute special code inside them.</p><p>Now, let’s re-create our fade animation exclusively using JavaScript.</p><h4><strong>Adding the hooks</strong></h4><pre>&lt;transition<br>    <a href="http://twitter.com/before">@before</a>-enter=&quot;beforeEnter&quot;<br>    <a href="http://twitter.com/enter">@enter</a>=&quot;enter&quot;<br>    <a href="http://twitter.com/after">@after</a>-enter=&quot;afterEnter&quot;<br>    <a href="http://twitter.com/enter">@enter</a>-cancelled=&quot;enterCancelled&quot;<br>    <a href="http://twitter.com/before">@before</a>-leave=&quot;beforeLeave&quot;<br>    <a href="http://twitter.com/leave">@leave</a>=&quot;leave&quot;<br>    <a href="http://twitter.com/after">@after</a>-leave=&quot;afterLeave&quot;<br>    <a href="http://twitter.com/leave">@leave</a>-cancelled=&quot;leaveCancelled&quot;<br>    :css=&quot;false&quot; &gt;<br>          &lt;div class=&quot;alert alert-success&quot; v-if=&quot;show&quot;  &gt;<br>              Let&#39;s animate using Javascript.<br>          &lt;/div&gt;<br>&lt;/transition&gt;</pre><p>As we plan on creating our animations exclusively using JavaScript, let’s inform VueJS, not to add the default CSS classes <strong><em>v-enter, v-enter-active, v-leave</em></strong> and <strong><em>v-leave</em></strong> active to the element. For this, we have to bind CSS as <strong><em>false</em></strong> (Boolean) as shown in the snippet above.</p><h4>Creating Methods</h4><pre>export default {<br>    data(){<br>        return {<br>            show : false<br>        }<br>    },<br>    methods : {<br>        beforeEnter(el){},<br>        enter(el,done){},<br>        afterEnter(el){},<br>        enterCancelled(el){},<br>        beforeLeave(el){},<br>        leave(el,done){},<br>        afterLeave(el){},<br>        leaveCancelled(el){}<br>    }</pre><pre>}</pre><p>Each method receives the <strong>element</strong> as a parameter with the <strong>enter</strong> and <strong>leave</strong> method receiving a second parameter — <strong><em>done. </em></strong>Now, done is actually a function which should be called once the animation completes. When using JavaScript animations VueJS has no means to determine how long each animation needs to be executed. This is where <strong><em>done()</em></strong> comes in to play.</p><p>Let’s see this in action as we modify the enter and leave methods.</p><p><strong>Enter Method</strong></p><pre>enter(el,done){<br>      var opacity = 0.1<br>      const interval = setInterval(() =&gt; {<br>        if (opacity &gt;= 1){<br>            clearInterval(interval);<br>            done();<br>        }<br>        el.style.opacity = opacity;<br>        el.style.filter = &#39;alpha(opacity=&#39; + opacity * 100 + &quot;)&quot;;<br>        opacity += opacity * 0.1;<br>      }, 10);</pre><pre>},</pre><p><strong>Leave Method</strong></p><pre>leave(el, done){<br>    var opacity = 1;  <br>    var interval = setInterval(() =&gt; {<br>        if (opacity &lt;= 0.1){<br>            clearInterval(interval);<br>            el.style.display = &#39;none&#39;;<br>            done();<br>        }<br>        el.style.opacity = opacity;<br>        element.style.filter = &#39;alpha(opacity=&#39; + opacity * 100 + &quot;)&quot;;<br>        opacity -= opacity *  0.1;<br>    }, 10);</pre><pre>},</pre><blockquote>Notice how we call the done() method where the animation ends.</blockquote><p>And that’s it. We are all done. Pretty neat. Ha ?</p><h3>Transition Groups</h3><p>So far we have seen how to animate a single item inside a transition element. What if we have a list of elements and we need to animate adding and removing items from the list ? Luckily, VueJS provides us <strong><em>Transition Groups</em></strong> to achieve the same with minimal effort.</p><pre>&lt;button class=&quot;btn btn-primary&quot; <a href="http://twitter.com/click">@click</a>=&quot;addColor&quot;&gt;<br>   Add Item<br>&lt;/button&gt;<br>&lt;br&gt;<br>&lt;ul class=&quot;list-group&quot;&gt;<br>    &lt;transition-group name=&quot;fade&quot;&gt;<br>        &lt;li<br>            class=&quot;list-group-item&quot;<br>            v-for=&quot;(color, index) in colors&quot;<br>            <a href="http://twitter.com/click">@click</a>=&quot;removeItem(index)&quot;<br>            style=&quot;cursor:pointer&quot;<br>            :key=&quot;color&quot;<br>            &gt;{{color}}<br>        &lt;/li&gt;<br>     &lt;/transition-group&gt;<br>&lt;/ul&gt;</pre><p>We have an array, <strong><em>colors </em></strong>declared as follows:</p><pre>colors : [&#39;Violet&#39;,&#39;Indigo&#39;,&#39;Blue&#39;,&#39;Green&#39;,&#39;Yellow&#39;,&#39;Orange&#39;]</pre><p>and methods <strong><em>removeItem</em></strong> and <strong><em>addColor</em></strong> as shown in the snippet below</p><pre>addColor(){<br>   this.colors.push(&quot;red&quot;);<br>},<br>removeItem(item){<br>   this.colors.splice(item,1);<br>},</pre><p>The transition-group works the same was a transition element works and adds the same classes to the items wrapped inside it.</p><blockquote>A transition-group requires each of the items wrapped inside to be identified by a unique key. In the snippet above, we are dynamically binding the key for the animations to work properly.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*cFMrWmGseS_NAJ_Y1UZEGA.gif" /></figure><p>Well, I guess that wraps it up. Feel free to leave a comment if you liked my article.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F88b4f9%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F88b4f9&amp;image=https%3A%2F%2Fe.enpose.co%2F%3Fkey%3DdRXnS9Gplk%26w%3D700%26h%3D425%26url%3Dhttps%253A%252F%252Fupscri.be%252F88b4f9%252F%253Fenpose&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e676f04f794fc27ff50adc1db7cfd49/href">https://medium.com/media/9e676f04f794fc27ff50adc1db7cfd49/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=115a0f5c6fbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>