<?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[Babystep - Medium]]></title>
        <description><![CDATA[Take baby steps to learn tech - Medium]]></description>
        <link>https://medium.com/babystep?source=rss----9ae525615af6---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Babystep - Medium</title>
            <link>https://medium.com/babystep?source=rss----9ae525615af6---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 06:56:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/babystep" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build 2048 from scratch using Vue.js (part 2)]]></title>
            <link>https://medium.com/babystep/build-2048-from-scratch-using-vue-js-part-2-e622a4c7e7a0?source=rss----9ae525615af6---4</link>
            <guid isPermaLink="false">https://medium.com/p/e622a4c7e7a0</guid>
            <category><![CDATA[transition-design]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Jason Buss]]></dc:creator>
            <pubDate>Sat, 16 Dec 2017 19:47:34 GMT</pubDate>
            <atom:updated>2017-12-22T15:44:27.952Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*E547zeakCruTHgCW5IH15A.gif" /><figcaption>2048</figcaption></figure><p>In this part of the tutorial we will talk about transitions and animations. Now that we have much of the core game functionality down, we can focus on making the play experience more pleasing and intuitive.</p><p>If you didn’t read the part 1 of this tutorial, you can find it <a href="https://medium.com/babystep/build-2048-from-scratch-using-vue-js-part-1-3bc555298ad5">here</a>.</p><p>To accomplish the desired affect, we will make use of 3 types of transitions / animations:</p><p><strong>List Transitions:</strong></p><ul><li><em>Tile Slide Movement</em></li><li><em>Game Menu Points</em></li></ul><p><strong>Conditional Rendering:</strong></p><ul><li><em>End Game Overlay</em></li></ul><p><strong>State transitions:</strong></p><ul><li><em>Game Menu Score</em></li><li><em>Tile Pop on Merge</em></li></ul><p>To understand the basics of transitions and animations, here are two great tutorials I’ve written — they will take you through all the core concepts of Vue.js transitions and how to create them.</p><p><a href="https://medium.com/babystep/vuejs-transitions-3842d8b633ae">https://medium.com/babystep/vuejs-transitions-3842d8b633ae</a> <a href="https://medium.com/babystep/vuejs-animations-javascript-md-fa496111d200">https://medium.com/babystep/vuejs-animations-javascript-md-fa496111d200</a></p><p>If you are unfamiliar with Vue.js transitions, it would be helpful to take a minute or two to skim through those guides. The first one will be the most helpful, it touches on the first 2 types of transitions we will be creating for the game. The new addition here will be state transitions.</p><h3>Tile Slide Movement</h3><p>So with the foundations of Vue.js transitions in mind, let’s dive in. Let’s first try to implement the tile sliding transition. This transition is the most important to the game, and without it the game is pretty unplayable.</p><p>Conceptually when we think about the board, we might invision it as a 2d array using the indices of each array to come up with an x, y coordinate of a tile. This is a great structure for doing tile manipulation, but when we try to apply transitions to this structure we will run into some problems. First, a group-transition in Vue.js operates on a (flat) list. A 2d array is actually a list of lists. This would reflect in a group-transition of group-transitions&#39;s. That might not initially raise any flags, but if we think about how group-transition&#39;s are triggered it becomes very obvious that doing any kind of vertical transition will be almost impossible with this structure. This is because the only ways to trigger the transition affect are through an enter, leave, or move. For a tile to move from board[0][0] to board[1][0] would mean that it would have to leave the board[0] list and enter the board[1] list. This can be done using javascript, but it will take some considerable computing to handle different sized boards, sliding of different lengths, and slide direction.</p><p>Don’t worry though, there is a much easier way to handle transitions. Going back to an earlier point, group-transition in Vue.js operates on a (flat) list. Let&#39;s think about the board again, does it really need to be a 2d array? For calculating the board on move, yes it makes sense to work with a 2d array, but for rendering the board, it doesn&#39;t matter. The grid structure can be accomplished through some fancy flexbox styling. In fact it would be easier and work within the Vue.js api if it were a flat array. So the strategy here can be 1 of 2 options:</p><ul><li>Store the board as a flat array, and chunk it into a 2d array anytime we need to calculate a move.</li><li>Store the board as a nested array and flatten it into a 1d array for rendering.</li></ul><p>The option I chose to move forward with was the first option. I feel this option is prefered because it feels more straigtforward.But because we are keying off each element with an id, both methods would work fine. Vue won’t have a problem detecting changes in the array and elements new position.</p><p>At this point you might be asking yourself — sure, but all of the list transitions I’ve seen so far have been vertically organized lists. How can a single group-transition handle both vertical and horizontal movement?</p><p>If you do some exploring on the Vue.js transitions documentation you’ll end up running across this section:</p><p><a href="https://vuejs.org/v2/guide/transitions.html#List-Move-Transitions">https://vuejs.org/v2/guide/transitions.html#List-Move-Transitions</a></p><p>In this section they show an example called Lazy Sodoku. Here the demonstrate that a single transition-groupelement can handle multidimensional grid transitions. How? All you need to do is organize the grid how you like using css, and make sure you apply the v-move class to each element in the group.</p><p>With these concepts in mind, let’s look at the code that makes this happen:</p><pre>// game.js</pre><pre>&lt;transition-group name=&quot;tile&quot; tag=&quot;div&quot; class=&quot;board&quot;&gt;<br>  &lt;tile v-for=&quot;tile in board&quot; :tile=&quot;tile&quot; :key=&quot;tile.id&quot;&gt;&lt;/tile&gt;<br>&lt;/transition-group&gt;</pre><pre>/* styles.css */</pre><pre>.board {<br>  display: flex;<br>  flex-wrap: wrap;<br>  width: 23em;<br>  padding: 6px;<br>  border-radius: 6px;<br>  background-color: rgba(58, 41, 76, 0.5);<br>}</pre><pre>.tile-move {<br>  transition: transform .09s ease;<br>}</pre><p>It’s as simple as that. We create a transition-group named tile. Using this, we can define our v-move class - .tile-move. This will create the sliding affect. We also define our board class which is a flex box that will wrap. There are many other ways to get the grid layout to work, but this is a quick and simple example.</p><h3>Game Menu Points &amp; Game Menu Score</h3><p>With the most important transition under our belt let’s look at the other group-transition on our list, the points increase transition, and the state transition of the score itself. The goal here is that anytime we score points in the game, we want to see our point total start ticking up by one until it reaches the new score, and also display a notice that fades in showing + &lt;point_number&gt; over our score. Since we just dealt with a group-transition let&#39;s handle that first. Here what we want to do is watch the score. Any time the score changes, we can observe its new and old value, and take the difference of the two to know how many points the player scored. Furthermore, knowing how much the points has increased we can display this number as points scored, and animate the score from its previous total to the new total. So let&#39;s look at the code to make this happen.</p><pre>// game-menu.js</pre><pre>watch: {<br>  score(newValue, oldValue) {<br>    const self = this</pre><pre>    if (newValue &gt; 0) {<br>      // must clone deep because when mutating (NOT replacing) an Array, <br>      // the old value will be the same as new value because they reference the same Array<br>      let oldPoints = _.cloneDeep(self.pointsIncrease)<br>      oldPoints.push(newValue - oldValue)<br>      self.pointsIncrease = oldPoints<br>    }<br>  },</pre><pre>  pointsIncrease(newPoints, oldPoints) {<br>    if (newPoints.length &gt; oldPoints.length) {<br>      setTimeout(() =&gt; {<br>        this.pointsIncrease.pop()<br>      }, 200)<br>    }<br>  }<br>},<br></pre><pre>// game-menu.js<br>// &lt;template&gt;</pre><pre>&lt;transition-group name=&quot;points&quot; tag=&quot;div&quot; class=&quot;points&quot;&gt;<br>  &lt;div v-for=&quot;(pointIncrease, index) in pointsIncrease&quot; :key=&quot;index&quot;&gt;+ {{ pointIncrease }}&lt;/div&gt;<br>&lt;/transition-group&gt;<br></pre><pre>/* styles.css */</pre><pre>.points-enter-active, .points-leave-active {<br>  transition: all 100ms;<br>}<br>.points-leave-to {<br>  opacity: 0;<br>  transform: translateY(-30px);<br>}<br>.points-enter {<br>  transform: translateY(30px);<br>}</pre><p>The idea here is that we are keeping a list of points increases. When we observe a points increase, we push that onto the list so that we can render it. This is so we can handle any number of points increases streaming into the game menu. To accomplish this, we are doing two things inside our watched properties. First we are watching the value of score. When it changes, and the new value is a positive integer, we will add the difference onto the list — pointsIncrease. One important gotcha when watching arrays in Vue, is that you must replace the array, or the watched value will not know what the old value was. This is because the reference in memory to the new and old arrays are the same. So this is why we use the cloneDeep method to make sure we make a new copy of the array. Next, inside our pointsIncrease watcher, we detect any time the length of the array increases - and set a timeout to remove whatever was added to the list. This will cause the enter / leave transitions to fire on our list, and make sure we don&#39;t leave any point increase notifications around.</p><p>Now for the next animation, the score itself. To reiterate, the affect we want to achieve, is to have the score tick up by 1 over some duration, ultimately landing on the final score. This is a fun animation and will give the game a sort of arcade’y feel. The strategy here will be to ‘tween’ the score from its current value to its desired value, updating and setting the inbe’tween’ value along the way. Let’s look at the code for this.</p><pre>// game-menu.js</pre><pre>data() {<br>  return {<br>    animatedScore: 0,<br>    pointsIncrease: [],<br>  }<br>},</pre><pre>watch: {<br>  score(newValue, oldValue) {<br>    const self = this</pre><pre>    if (newValue &gt; 0) {<br>      // must clone deep because when mutating (NOT replacing) an Array, <br>      // the old value will be the same as new value because they reference the same Array<br>      let oldPoints = _.cloneDeep(self.pointsIncrease)<br>      oldPoints.push(newValue - oldValue)<br>      self.pointsIncrease = oldPoints<br>    }</pre><pre>    function animate () {<br>      if (TWEEN.update()) {<br>        requestAnimationFrame(animate)<br>      }<br>    }<br>    new TWEEN.Tween({ tweeningNumber: oldValue })<br>      .easing(TWEEN.Easing.Quadratic.Out)<br>      .to({ tweeningNumber: newValue }, 500)<br>      .onUpdate(function () {<br>        self.animatedScore = this.tweeningNumber.toFixed(0)<br>      })<br>      .start()<br>    animate()<br>  },<br>  <br>  ...</pre><p>Here we see the same code as before but with the addition of two functions, the animate function, and the Tween function. You can see that the Tween function starts at oldValue, and tweens to newValue over the duration of 500ms. And, onUpdate, or on each tick, we set a data attribute on the game-menu component animatedScore equal to the tweened number rounded to an integer. That is the meat of the animation!</p><p>The last transition on this page is the game over screen. This one is the easiest of all the transitions. It is a conditional rendering of our game-over div. The idea here is that we will pass in the game-state as a prop to the game-menu component, a boolean saying whether or not the game is over. And, we will render the game-over menu whenever that boolean is true.</p><pre>// game-menu.js</pre><pre>...</pre><pre>// &lt;template&gt;<br>&lt;transition name=&quot;fade&quot;&gt;<br>  &lt;div v-if=&quot;gameOver&quot; class=&quot;modal&quot;&gt;<br>    &lt;h1&gt;Game Over!&lt;/h1&gt;<br>    &lt;a class=&quot;button button-black&quot; @click=&quot;newGame()&quot;&gt;Try again&lt;/a&gt;<br>  &lt;/div&gt;<br>&lt;/transition&gt;</pre><pre>...</pre><pre>// &lt;Component&gt;<br>props: {<br>  gameOver: {<br>    type: Boolean,<br>    required: true,<br>  }<br>},</pre><pre>...</pre><pre>/* styles.css */</pre><pre>.fade-enter-active {<br>  transition: opacity 2s<br>}<br>.fade-leave-active {<br>  transition: opacity .5s<br>}<br>.fade-enter, .fade-leave-to {<br>  opacity: 0<br>}</pre><h3>Tile Pop on Merge</h3><p>The last transition we will look at will be the tile pop animation whenever it increases in points. The affect we are looking to achieve is a quick scale up and down of the tile whenver another tile merges with it. We will do this the same way we handled the score animation, using a watched property. Let’s see the code.</p><pre>// tile.js</pre><pre>watch: {<br>  value(newVal, oldVal) {<br>    if (newVal &gt; oldVal) {<br>      setTimeout(() =&gt; {<br>        Velocity(this.$el, {scale: 1.2}, {duration: 50, complete: () =&gt; {<br>          Velocity(this.$el, {scale: 1}, {duration: 50})<br>        }})<br>      }, 50)<br>    }<br>  }<br>},</pre><p>Here we are simply watching the value of any tile, and when the newValue is greater than the oldValue we will scale the element up and down by 20% over the course of 100ms.</p><p>That’s all the animations! Now the game should look great and feel responsive!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e622a4c7e7a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/babystep/build-2048-from-scratch-using-vue-js-part-2-e622a4c7e7a0">Build 2048 from scratch using Vue.js (part 2)</a> was originally published in <a href="https://medium.com/babystep">Babystep</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build 2048 from scratch using Vue.js (part 1)]]></title>
            <link>https://medium.com/babystep/build-2048-from-scratch-using-vue-js-part-1-3bc555298ad5?source=rss----9ae525615af6---4</link>
            <guid isPermaLink="false">https://medium.com/p/3bc555298ad5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Marshall Shen]]></dc:creator>
            <pubDate>Fri, 27 Oct 2017 11:36:03 GMT</pubDate>
            <atom:updated>2017-10-27T11:35:48.216Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*ZDXJteMc09XDbJDh9NX3DQ.gif" /><figcaption>what we will build</figcaption></figure><p>2048 is a popular single-player game. The game has a 4 by 4 grid for <strong>tiles</strong>. Each <strong>tile</strong> can either be empty or has a <strong>card</strong> with value. As a player, you can move <strong>left</strong>, <strong>right</strong>, <strong>up</strong> and <strong>down</strong>. As cards get merged, the numbers on the cards change as well. The goal is to get number on the card as high as possible. The game ends when all the tiles are full and there are no next moves left.</p><p>You can find the demo project <a href="http://babystep.io/2048/">here</a>, and the Github repo <a href="https://github.com/babystep-io/2048">here</a>. In this blog post (part 1) and next blog post (part 2) we will walk through how we build the game step by step!</p><h3>Get started with project scaffold</h3><p>First, we need to set up a project scaffold to build a Vue project. We are going to use plain javascript so that we can understand what is going on. Let’s start by cloning the <a href="https://github.com/babystep-io/PlainJS-Vue-scaffold">plain javascript Vue scaffold</a>. The scaffold provides several directories for us:</p><ul><li><strong>assets</strong>. All third party javascript library, stylesheets, and images.</li><li><strong>components</strong>. All native Vue components.</li><li><strong>mixins</strong>. All native Vue mixins.</li><li><strong>store</strong>. Vuex store for state management.</li><li><strong>main.js</strong>. The place where a new Vue instance is initiated.</li><li><strong>index.html</strong>. The place where the whole app is displayed.</li></ul><h3>Step 1. set up game board</h3><p>In this step we will:</p><ol><li>create game component with board</li><li>create shadow board</li><li>create seeding function</li></ol><p>First we have a game component that is in charge of a <strong>board</strong>. A <strong>Board</strong> has many <strong>tiles</strong>, and each <strong>tile</strong> has a <strong>value</strong> that defaults to 0. We can start by registering the component game:</p><p><strong>src/components/game.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div class=&quot;game&quot;&gt;<br>    &lt;/div&gt;<br>  `</pre><pre>Vue.component(&quot;game&quot;, {<br>    template: html,<br>    data () {<br>      return {<br>        board: [],<br>      }<br>    },<br>  })<br>}))()</pre><p>On the Vue component game, we have a data property board that holds an array of <strong>tiles</strong>, each tile holds a default value of 0. Next we add a <strong>shadow board</strong> as the base layer of the board game inside our html.</p><p><strong>src/components/game.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div class=&quot;game&quot;&gt;<br>      &lt;div class=&quot;game-container&quot;&gt;<br>       &lt;div class=&quot;board shadow-board&quot;&gt;<br>          &lt;div v-for=&quot;n in board.length&quot; :key=&quot;n&quot; class=&quot;tile shadow-tile&quot;&gt;&lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `<br>  ...<br>}))()</pre><p>Now when you open index.html, it should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*Nssm3GE9myrzxtVwXDyhpg.png" /><figcaption>shadow board</figcaption></figure><p>In order to begin the game and keep playing, we need to give some tiles a playable value (i.e. value &gt; 0). For this we will create a <strong>seedTwo()</strong> method. At the start of each game we will use this to create the starting state, and after a valid move we will use this to keep the game moving forward</p><p><strong>src/components/game.js</strong></p><pre>Vue.component(&quot;game&quot;, {<br>  ...<br>  methods: {<br>    <strong>seedTwo</strong>() {<br>      const self = this</pre><pre>      let getRandomItem = function() {<br>        let row =   <br>           self.board[Math.floor(Math.random()*self.board.length)]<br>        return row[Math.floor(Math.random()*row.length)]<br>      }</pre><pre>      let initialRandomItem = getRandomItem()</pre><pre>      while (initialRandomItem.value != 0) {<br>        initialRandomItem = getRandomItem()<br>      }</pre><pre>      initialRandomItem.value = 2<br>    }<br>  }<br>})</pre><pre>...</pre><h3>Step 2. define object models</h3><p>In this step we will:</p><ol><li>create Tile() component</li><li>modify Tile() CSS class based on wether the tile is empty or not</li><li>create GameMenu() component</li></ol><p>A board can hold 16 tiles as a flat array, although we will present it on the board as a 2 dimensional array. We add another component tile under src/components/tile.js. The <strong>tile</strong> components take a tile object as <a href="https://vuejs.org/v2/guide/components.html#Props">a required props</a>, which needs to include {value: X} as part of the object.</p><p><strong>src/components/tile.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div class=&quot;tile&quot;&gt;<br>      {{ value }}<br>    &lt;/div&gt;<br>  `</pre><pre>Vue.component(&quot;tile&quot;, {<br>    template: html,<br>    props: {<br>      tile: {<br>        type: Object,<br>        required: true<br>      },<br>    },</pre><pre>computed: {<br>      value() {<br>        return this.tile.value<br>      },<br>    }<br>  })<br>}))()</pre><p>Notice that in our final product, the style of each tile change as we change the a tile from being empty (value 0) to non-empty (value not 0). Inside the component, we construct computed properties based on the value, and later on we use the computed property to toggle the style by <a href="https://vuejs.org/v2/guide/class-and-style.html">class binding</a>:</p><p><strong>src/components/tile.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div class=&quot;tile&quot;&gt;<br>      {{ displayingValue }}<br>    &lt;/div&gt;<br>  `</pre><pre>Vue.component(&quot;tile&quot;, {<br>    template: html,<br>    props: {<br>      tile: {<br>        type: Object,<br>        required: true<br>      },<br>    },</pre><pre>    computed: {<br>      value() {<br>        return this.tile.value<br>      },</pre><pre><strong>     displayingValue() {<br>       if (this.value &gt; 0) {<br>         return this.value<br>       }</strong></pre><pre><strong>       return null<br>     },</strong></pre><pre><strong>     emptyTile() {<br>      return this.displayingValue === null<br>     },</strong><br>    }<br>  })<br>}))()</pre><p>Given we have a <strong>tile</strong> component, we plug the tile back in the <strong>game</strong> component:</p><p><strong>src/components/game.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div class=&quot;game&quot;&gt;<br>      &lt;div class=&quot;game-container&quot;&gt;<br>    <strong>    &lt;tile v-for=&quot;tile in board&quot; :tile=&quot;tile&quot; :key=&quot;tile.id&quot;&gt;&lt;/tile&gt;</strong><br>        &lt;div class=&quot;board shadow-board&quot;&gt;<br>          &lt;div v-for=&quot;n in board.length&quot; :key=&quot;n&quot; class=&quot;tile shadow-tile&quot;&gt;&lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `<br>  ...<br>}))()</pre><p>Now that we have the computed property emptyTile, we can plug into our html and toggle class:</p><p><strong>src/components/tile.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div class=&quot;tile&quot; <strong>v-bind:class=&quot;{&#39;tile-empty&#39;: emptyTile}</strong>&quot;&gt;<br>      {{ displayingValue }}<br>    &lt;/div&gt;<br>  `</pre><pre>Vue.component(&quot;tile&quot;, {<br>    ...<br>  })<br>}))()</pre><p>Next we can define a game-menu to show current score, show the best score, and start a new game. Let&#39;s start with a plain scaffold:</p><p><strong>src/components/game-menu.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div class=&quot;game-menu&quot;&gt;<br>      &lt;div class=&quot;row&quot;&gt;<br>        &lt;div class=&quot;title&quot;&gt;2048&lt;/div&gt;<br>        &lt;div class=&quot;scores space-right&quot;&gt;<br>          &lt;div class=&quot;score&quot;&gt;<br>            &lt;div class=&quot;score-title&quot;&gt;SCORE&lt;/div&gt;<br>            &lt;div class=&quot;score-value&quot;&gt;0000&lt;/div&gt;<br>          &lt;/div&gt;<br>          &lt;div class=&quot;score&quot;&gt;<br>            &lt;div class=&quot;score-title&quot;&gt;BEST&lt;/div&gt;<br>            &lt;div class=&quot;score-value&quot;&gt;0000&lt;/div&gt;<br>          &lt;/div&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;a class=&quot;button space-right&quot;&gt;New Game&lt;/a&gt;<br>    &lt;/div&gt;<br>  `</pre><pre>Vue.component(&quot;game-menu&quot;, {<br>    template: html,<br>  })<br>}))()</pre><p>Let’s wire up the “New Game” button! Because game-menu component is nested inside game component. We can consider game-menu as the child component for the parent component game. Vue has a nice paradigm for child-parent communication where a child component can <strong>emit</strong> events up to parent component and let the parent handle the event. This paradigm is called &quot;data down, event up&quot;. You can read more about Vue events handling <a href="https://vuejs.org/v2/guide/events.html">here</a>.</p><p>So let’s register the events on game-menu.js</p><p><strong>src/components/game-menu.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div class=&quot;game-menu&quot;&gt;<br>      ...<br>      &lt;a class=&quot;button space-right&quot; <strong>@click=&quot;newGame()&quot;</strong>&gt;New Game&lt;/a&gt;<br>    &lt;/div&gt;<br>  `</pre><pre>Vue.component(&quot;game-menu&quot;, {<br>    template: html,</pre><pre>    methods: {<br>      <strong>newGame() {<br>        this.$emit(&quot;new-game&quot;)<br>      }</strong><br>    }<br>  })<br>}))()</pre><p><strong>this.$emit(“new-game”)</strong> sends an event up to its parent game, and inside game.js we need to handle the event. When an event new-game is received, the game component will call <strong>newGame()</strong> method, which resets the board and seed two tiles by calling <strong>seedTwo()</strong> twice.</p><p><strong>src/components/game.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div class=&quot;game&quot;&gt;<br>      &lt;game-menu <strong>@new-game=&quot;newGame()&quot;</strong>&gt;&lt;/game-menu&gt;<br>      ...<br>    &lt;/div&gt;<br>  `</pre><pre>  Vue.component(&quot;game&quot;, {<br>    template: html,<br>    ...<br>    methods: {<br>      seedTwo() {<br>        ...<br>      },</pre><pre>   <strong>   newGame() {<br>        this.resetBoard()<br>        this.seedTwo()<br>        this.seedTwo()<br>      },</strong></pre><pre>      resetBoard() {<br>        this.board = Array.apply(null, { length: 16 })<br>          .map(function (_, index) { <br>           return { id: index, value: 0 }<br>        })<br>      }<br>    }<br>  })<br>}))()</pre><h3>Step 3: Implment Merge and slide tiles</h3><p>In this step we will:</p><ol><li>Using moveRight() as an example, understand how to merge and slide tiles algorithmically</li><li>Using moveRight() as an example, implement the merge and slide</li><li>Register controls in the game component using <a href="https://vuejs.org/v2/guide/mixins.html">Vue mixin</a></li></ol><p>We essentially have four different methods to implement moveRight, moveLeft, moveUp and moveDown. Once we implement one method, the rest of them follow the same pattern and thus easier to implement. Let&#39;s take moveRight() as an example to walk through.</p><p>moveRight() essentially includes two steps: <strong>merge</strong> and <strong>slide</strong>. In merge step, we figure out the two tiles that need to combine into one; in sldie step, we figure out the future position of each tile. Because we are moving horizontally for moveRight(), the algorithm scan through each row and trigger <strong>mergeRight</strong> then <strong>slideRight</strong>. The animation below demonstrates how the algorithm of moveRight() works on one row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*nrTejObW7zEebb1Hxvknyw.gif" /><figcaption>step 1: merge</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*T7_q_hU3ni2pNj9u3zVt3Q.gif" /><figcaption>step 2: slide</figcaption></figure><p>The below is the code that implements the algorithm for moveRight():</p><p><strong>src/mixins/control.js</strong></p><pre><strong>mergeRight(board, a)</strong> {<br>  let i = board.length - 2<br>  let j = board.length - 1<br>        <br>  while (i &gt;= 0) {<br>   if (board[a][i].value === 0 &amp;&amp; board[a][j].value === 0) { <br>   // if both elements are zero<br>     j --<br>     i --<br>   } else if (board[a][i].value === board[a][j].value) { <br>   // if two elements have same value</pre><pre>     board[a][j].value = board[a][i].value + board[a][j].value<br>     board[a][i].value = 0<br>     <br>     j--<br>     i--<br>   } else if (board[a][j].value === 0) { <br>   // if the right most has 0<br>     j--<br>     i--<br>   } else if (board[a][i].value != 0 &amp;&amp; board[a][j].value != 0 &amp;&amp; (i + 1 == j)) { // if both are non zero and next from each other<br>     j--<br>     i--<br>   } else if (board[a][i].value != 0 &amp;&amp; board[a][j].value != 0) { <br>     // if both are non zero and not next from each other<br>     j--<br>   } else if (board[a][i].value === 0) { <br>     // if the left most element is zero<br>     i--<br>   }<br>  }<br>},</pre><pre><strong>slideRight(board, a)</strong> {<br>  let k = board.length - 2<br>  let l = board.length - 1<br>  while (k &gt;= 0) {<br>    if (board[a][l].value !== 0) { <br>      // if right most element is 0<br>      l --<br>      k --<br>    } else if (board[a][l].value !== 0 &amp;&amp; board[a][k].value !== 0) {      <br>      // if right most and left most elements are not 0<br>      l --<br>      k --<br>    } else if (board[a][l].value === 0 &amp;&amp; board[a][k].value === 0) { <br>      // if right most and left most elements are 0<br>      k --<br>    } else if (board[a][l].value === 0 &amp;&amp; board[a][k].value !== 0) { <br>      // if right most element is 0 and left most element is not 0<br>      board[a][l].value = board[a][k].value + board[a][l].value<br>      board[a][k].value = 0<br>      l --<br>      k --<br>    }<br>  }<br>}</pre><p>After we implement moveRight, moveLeft, moveUp and moveDown. We can isolate all those methods in src/mixins/control.js, and then we can include the <strong>control</strong> as an mixin for game component. Now when a game is mounted, we register the controls:</p><p><strong>src/components/game.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    ...<br>  `</pre><pre>  Vue.component(&quot;game&quot;, {<br>    template: html,<br><strong>    mixins: [window.app.mixins.control],<br></strong>    ...<br>    methods() {<br>      setupBoard() {<br>        this.newGame()<br><strong>        this.registerControl()<br></strong>      }</pre><pre>    }</pre><pre>  })<br>}))()</pre><p>We have come pretty far in this blog post! In part 2 of this blog series, we will walk through how to:</p><ol><li>Add FLIP animation to our tiles movement using Vue.js</li><li>Use Vuex to track scores and state of a game.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bc555298ad5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/babystep/build-2048-from-scratch-using-vue-js-part-1-3bc555298ad5">Build 2048 from scratch using Vue.js (part 1)</a> was originally published in <a href="https://medium.com/babystep">Babystep</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delivering an experience one game at a time.]]></title>
            <link>https://medium.com/babystep/lets-play-849ed08dda0?source=rss----9ae525615af6---4</link>
            <guid isPermaLink="false">https://medium.com/p/849ed08dda0</guid>
            <category><![CDATA[game-design]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Kyle Reden]]></dc:creator>
            <pubDate>Tue, 17 Oct 2017 20:21:26 GMT</pubDate>
            <atom:updated>2017-10-17T20:21:26.333Z</atom:updated>
            <content:encoded><![CDATA[<p>Growing up I had a huge imagination and loved to play games. This could be board games, video games, card games, games outside with friends, make believe, or any number of other things. When it came right down to it I just wanted to have fun.</p><p>I had a ton of toys too, a whole chest full of them (that I feel asleep in once!) but I would often find myself picking up anything around me and “turning” it into something else. A hammer held by its head would become a machine gun or if I flipped it so that it was flat then I had a dreadnaught starship (creatively named <em>The Hammer</em>). Much to his lament, my dads tool chest became a whole new playground for me!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IBNrThqIn5kvLfpT.jpg" /><figcaption>Hammers are so useful</figcaption></figure><p>As I got older this ability never went away but my focus shifted more and more toward video games. I played the classics on the 90’s consoles but I count my first real video game addiction as <a href="https://en.wikipedia.org/wiki/Unreal_Tournament">Unreal Tournament</a>. My brother introduced me to it one fateful day, I walked into the den and saw him playing something new on the computer. I was immediately entranced by how fast things were moving and all the gore. He noticed me and asked if I wanted to try? I excitedly replied “Yes!”. I remember sitting down, him placing my hand over WASD (I can remember how foreign that felt! I was only used to home row at that point) and telling me what to do. I immediately died several times but then it happened, I got my first kill! I was hooked from that moment on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P8CV_by8URO8abF4.jpg" /><figcaption>Ahhhh yeah!</figcaption></figure><p>This lead to a lifelong obsession with video games. Battlefield 1942, Medal Of Honor: Allied Assault, Anarchy Online, Diablo II, and the Half Life series are just a few of the games that dominated my teenage years. Going into college I decided that I wanted to study the medium that I spent so much of my time on so I majored in video game design. I threw myself into my studies (as much as someone with undiagnosed ADD could) and realized that I had a passion for all things games.</p><p>I learned how to analyze games and I became very good at it, so good that for a time I couldn’t actually have fun playing a game because I was too busy asking questions: <em>Why did they do it this way? Was this intentional or an artifact from that other thing that they decided to leave in? Why is this element fun?</em></p><p>These days I play more games that I make but I will always be a student of them. When I play them I am constantly analyzing them, breaking them down into their base elements to discover how they work and why they are fun. Recently I had a conversation with someone that made me think “Hey, you should write something about this!” and so here I am.</p><h3>What are games really?</h3><blockquote><em>… Games are merely a means to an end. On their own, games are just artifacts — clumps of cardboard of bags of bits. Games are worthless unless people play them. Why is this? What magic happens when games are played?</em></blockquote><blockquote><em>When people play games, they have an experience. It is this experience that the game designer cares about. Without the experience, the game is worthless.</em></blockquote><blockquote><em>— Jessie Schell, </em><a href="https://www.amazon.com/Art-Game-Design-Lenses-Second/dp/1466598646/">The Art of Game Design: A book of Lenses</a></blockquote><p>A game is really a <strong>delivery mechanism</strong> for an <em>experience</em>. That experience can be anything from flying a plane to being a space marine to getting ridiculed by a dog because of your terrible aim. Whatever it might be, conveying an experience is the reason we make games and taking part in it is the reason we play them.</p><p>But how does one make a compelling experience? I don’t think there is any one, or right, answer to this question but here are a few things that I think can help:</p><ol><li>Listen to who you want to partake in the experience you are creating. Find out what makes them happy and excited. Listen to the feedback they give you along the way. Your audience is going to be a huge help in making something wonderful.</li><li>Learn about the human mind. Learning how we as humans perceive things will help to inform how to create experiences that seem real even though that are not.</li><li>Be informed about the experience you are trying to create. <em>Red Dead Redemption</em> did a spectacular job of delivering to the player the experience of being in the wilderness because they learned what the sounds and sights would be.</li><li>Get your game out there as soon as you can so that people can play test it. You may have the most compelling experience ever but the game is the vehicle and if that vehicle doesn’t function properly then it wont deliver the experience very well (if at all!).</li></ol><h3>Games are made up of elements</h3><p>If the game is the vehicle, gameplay elements are what that vehicle are made of. The mechanics, rules, controls, items, power-ups, and basically everything else are all gameplay elements. You can almost think of these as tiny vehicles that deliver tiny experiences that all add up to the major experience you are trying to create. Having the right elements is key and you must take care to include what is needed and get rid of what might be an impediment to delivering something wonderful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*_0qsaeENKuKauMkP.jpg" /><figcaption>Gameplay elements are kinda like pieces to a puzzle.</figcaption></figure><p>You must also be as flexible as possible with these elements. You might start off thinking that you want your game to be a first person shooter and go down that path, bringing in all the traditional elements of a FPS. Soon though, you may realize that actually this game is better suited having an isometric view meaning that you need to rework basically the rest of the game. That’s okay! It might be frustrating but remember, as a game designer you are only really concerned the experience and the game is just our way of delivering it!</p><p>Let’s take a look at a game that in my humble opinion does a fantastic job of delivering an incredible and enjoyable experience: <a href="http://store.steampowered.com/app/400/Portal/"><em>Portal</em></a></p><h3>Portal</h3><p><em>Portal</em> is a first person puzzle game made by Valve that was released on October 9th, 2007 as a part of the Orange Box. You play as Chell, a silent protagonist trying to survive a series of puzzles being administered by a homicidal and snarky AI named GLaDOS. You complete these puzzles with the help of your portal gun, physics, and some simple objects in each level. Honestly if you have not played this game, stop reading this and go play it right now. I promise you will not be disappointed!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*WP4j0pkckbWAr1CU.png" /><figcaption>GLaDOS: Pre potato years</figcaption></figure><h4>Gameplay Elements</h4><p><em>Portal</em> can really be broken down into a handful of gameplay elements that deliver its experience:</p><ul><li>Puzzles</li><li>First Person</li><li>Physics</li><li>Simple objects (I love my companion cube)</li><li>Story</li><li>Single Player</li><li>Humor</li><li>Cake</li></ul><p>The gameplay elements are simple but they are woven together to create something fantastic:</p><ul><li>The puzzles start off simple, getting harder as the game progresses. As the player completes them they get the experience of solving something.</li><li>To complete these puzzles the player must use some physics and simple objects. A first person perspective makes it easier (and more thrilling!) to gauge arcs before you hurl yourself through the air.</li><li>When a puzzle is completed the player experiences a feeling accomplishment as well anticipation for the next puzzle</li><li>The story paints the main character as the only one left alive in a large complex that seems to have once been a large laboratory. As you progress through the game you are constantly reminded that people used to occupy this space but for some reason you are the only one left. The game being single player really helps to drive the experience of isolation home.</li><li>The characters…or really the antagonist (since she is the only one that talks) employ a wonderfully dark and sarcastic sense of humor. GLaDOS just want’s to murd…gather data through tests but along the way she will say somethings that are really kind of messed up. The “WTF is going on” experience along with the experience of feeling like this robot might be trying to kill you is delivered quite well.</li><li>And at the end of all the tests you will get to experience some cake. Everybody loves cake!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/0*prVsSGnKB7YJaXZ6.jpg" /><figcaption>It’s a lie.</figcaption></figure><p><em>Portal</em> also employs something else that makes the experience it delivers amazing: Emergent Gameplay.</p><h4>Emergent Gameplay</h4><blockquote><em>… Nothing can be more rewarding for the player than when he tries some obtuse, unobvious method for solving a puzzle or a combat situation and it actually works.</em></blockquote><blockquote><em>— Richard Rouse III, </em><a href="https://www.gamasutra.com/view/feature/131472/game_design__theory_and_practice_.php?page=1">Game Design: Theory &amp; Practice</a></blockquote><p>Emergent gameplay is enabled by a game that has well defined complex systems and rules that the player can easily understand. Through this understanding they begin to explore and test the boundaries of the world to come up with solutions to the problems presented to them and these solutions may not be something the game designer ever thought of.</p><p><em>Portal</em> pulls this off masterfully. There are multiple ways to solve most of the puzzles in the game. This leads players to having unique solutions which in turn leads to players sharing those solutions with others. These other players then go back and play the game again to see if a puzzle can really be solved in this new way. This delivers an experience of shared play, discoveries, problem solving, and teamwork that no one expects from a single player game!</p><p>The elements <em>Portal</em> uses are not in themselves unique but the way they are woven together make this game one of the best examples of how a game can deliver and experience that is wonderful, unique, and memorable.</p><h3>Let’s make a game</h3><p>Making a game, delivering an experience, is hard and there is no right or wrong way to do it. My process thus far has been:</p><ul><li>Write down my idea</li><li>Flesh out the gameplay elements</li><li>Prototype those elements to see if they work together like I want them to</li><li>Start building the actual game</li></ul><p>You might notice I am missing a step about figuring out the experience but I have found that the idea is actually the experience in most cases. For example, the game idea might be “A game about being a medic in WW2” informing me that the over all experience I am trying to achieve is being a medic.</p><p>You don’t have to be a programmer to make a game. You don’t even need a computer! Board games are a great way to get into game making. If you do want to go the computer route I suggest checking out <a href="https://unity3d.com/">Unity Game Engine</a>. It has a free version and great documentation. Also check out the books I quoted in this, they are both stuffed full of great knowledge on how to make games.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=849ed08dda0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/babystep/lets-play-849ed08dda0">Delivering an experience one game at a time.</a> was originally published in <a href="https://medium.com/babystep">Babystep</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[design a mobile app from scratch]]></title>
            <link>https://medium.com/babystep/design-a-mobile-app-from-scratch-b0935d068372?source=rss----9ae525615af6---4</link>
            <guid isPermaLink="false">https://medium.com/p/b0935d068372</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[prototyping]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[interaction-design]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Marshall Shen]]></dc:creator>
            <pubDate>Thu, 12 Oct 2017 02:49:42 GMT</pubDate>
            <atom:updated>2017-10-12T02:49:32.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*gujVNk7a3tqwvQ0o.png" /></figure><p>During the past two months I designed a mobile app Chefy from scratch, the app helps people to discover food holidays and find interesting events for the holidays. As a trained developer, I really enjoy the challenge of putting on my designer’s hat and start an idea from zero to “ready for development”. This blog post describes my journey in designing this app. The link to the finalized prototype can be found <a href="https://marvelapp.com/a454fae">here</a>.</p><h3>Brainstorm and research user need</h3><p>I didn’t come up with the single idea of food holiday in the beginning. Rather, it’s a mixture of brainstorming and observation. I start to draft out the ideas I want to do, identify the audience of my ideas, and then interview potential users. During the brainstorming session, I kept an open mind about which ideas to pursue. I put more emphasis on observing user behavior and asking questions. My goal at this stage is to gather valuable information and insights during research.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fSrDl4L7if4ZXjta.jpg" /></figure><h3>Prototype, feedback, repeat</h3><p>After insight gathering, I got down to business and started sketches. To understand the user flow, I started with drawing out user stories. I captured some key moments in an experience in which the user interacts with the app, and how the app makes the user think and feel. This visualization exercise helps me look at all information in a different lens, and I had a few new ideas on how to make the app better while making those user story sketches.</p><p>Next, I started drawing paper prototypes based on my understanding of user stories. Paper prototypes allow designers to quickly demonstrate the idea and raw functionality of the app. In addition, I came up with multiple versions of paper prototypes in order to receive a wide range of feedback. After the paper prototypes are done, I showed them to potential users, received more feedback on different versions, then iterate again.</p><p>The general flow of prototypes is from paper prototype to low fidelity, then to high fidelity. My key takeaway during this process is about fast iteration. Start producing design sketches of large volume, gather feedbacks from test users, then make changes again rapidly.</p><p>Below is an example of paper prototype:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*4hEyUipYejRUvfyk.png" /></figure><p>Below is an example of low fidelity prototype:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*Tt3lVhX5kcj0itrO.jpg" /></figure><p>Below is an example of high fidelity prototype:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*XhNoE6sWICUCKX1J.png" /></figure><h3>User testing</h3><p>Testing the effectiveness of the design is a big component of design, and this is something I want to get better at too. There are different flavors of user testing as well:</p><ul><li><strong>Peer review</strong>. Fellow designers review design work. This process allowed me to capture heuristic flaws early on, so when I have time to do user testing, I save some time by correcting some obvious design mistakes.</li><li><strong>Onsite testing</strong>. Conduct user testing with a user at the physical location. This allowed me to observe users better and noticed some design flaws just by watching them interact with the app. However, it also introduced bias because users tend to be nice with the testers and less vocal about the flaws they see in the prototype.</li><li><strong>Remote testing</strong>. Conduct user testing with websites such as usertesting.com. This gave me access to a lot of targeted audience with various backgrounds. In addition, the service provides standard templates to ask questions. The reports come from the website is very informative, the feedback is a lot more constructive.</li></ul><p>One thing I want to get better at is how to ask questions. I found myself give answers to users when I see them stuck on certain screens of the prototype. However, I should treat those moments as an opportunity to understand why they stuck and discover any improvements I can make on the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ekzqz_0xiJ7nv7MF.jpg" /></figure><p>Marshall Shen © 2017</p><p><em>Originally published at </em><a href="http://himarsh.org/design-a-mobile-app-from-scratch/"><em>himarsh.org</em></a><em> on October 11, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0935d068372" width="1" height="1" alt=""><hr><p><a href="https://medium.com/babystep/design-a-mobile-app-from-scratch-b0935d068372">design a mobile app from scratch</a> was originally published in <a href="https://medium.com/babystep">Babystep</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 things I learned from interaction design specialization on Coursera]]></title>
            <link>https://medium.com/babystep/5-things-i-learned-from-interaction-design-specialization-on-coursera-ed60ce86b30c?source=rss----9ae525615af6---4</link>
            <guid isPermaLink="false">https://medium.com/p/ed60ce86b30c</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[interaction-design]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[coursera]]></category>
            <dc:creator><![CDATA[Marshall Shen]]></dc:creator>
            <pubDate>Thu, 12 Oct 2017 02:26:59 GMT</pubDate>
            <atom:updated>2017-10-12T02:26:51.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JgfDpvAXbH4os5H1.png" /></figure><p>For the past year I’ve been studying <a href="https://www.coursera.org/specializations/interaction-design">Interaction Design Specialization on Coursera</a>. This series of courses taught me mindset and techniques of a designer. Design is everywhere, and a design-oriented mindset allows us to see the world in different ways. At its core, designers are problem identifiers and problem solvers, and everyone can strive to be a designer. So what have I learned from this specialization?</p><h3>1. Design has its workflow</h3><p>The process of design originates from user needs, and ends with an outcome that address the identified need. On a high level, design has following states:</p><ul><li><strong>Needfinding</strong>. We start out by observing what people do now, stay curious, and ask questions to clarify any problems.</li><li><strong>Ideation</strong>. Brainstorm problems out of the observation, and brainstorm solutions for the problems.</li><li><strong>Prototype</strong>. Start with paper prototype, and get feedback from the user, modify the paper prototype based on feedback.</li><li><strong>Heuristic Evaluation</strong>. Refine the prototype by thinking about usability heuristics, get critics from other designers based on heuristics, see <a href="https://www.nngroup.com/articles/ten-usability-heuristics/">ten design heuristics by Jakob Nielson</a>.</li><li><strong>Plan &amp; A skeleton</strong>. Sketch out development plan of designing the product (e.g. on a weekly cadence), and iterate on the plan (e.g. build high-fidelity prototype).</li><li><strong>Draft out testing plans</strong>. Think about what it is we want to test, and set up experiments.</li><li><strong>Test prototype</strong>. Conduct user testing sessions based on testing plan, iterate on refining the product.</li></ul><h3>2. Design is iterative</h3><p>No one gets a design right at first shot. It requires rounds of brainstorming, prototyping and testing to generate a design that hit the bull’s eye. Design process is iterative by nature, and the focus should be on the marginal improvements during each iteration. After each round of design iteration, we should have a better grasp of problems we try to solve.</p><h3>3. Stay curious, not judgemental</h3><p>One big mindset challenge for being a designer is how we receive and process feedback. When we design prototypes and get it in front users, any critics or negative feedback might hurt our personal feelings. As designers, our goal is to identify a user problem, and apply design to solve it. Instead of thinking about “this is my design” and getting personally attached, we can stay curious and focus on more problem-solving questions, such as:</p><ul><li>what are the real problem(s) for the users?</li><li>what are some solution(s) to address the problem(s)?</li><li>how to measure whether the solution(s) addresses problem(s)?</li></ul><p>Such mindset removes personal attachment from the solution, and we switch from being judgemental about the feedback to being curious about the feedback.</p><p>One of my misunderstanding on design is that design is about “making things pretty”. Product design is centered around information and user interaction with relevant information. The primary focus should be user-centric and information-centric. For example, in designing for interactions, we should keep in mind that <em>search and navigation go together</em>, and we should emphasize on <em>discover-ability</em> and <em>feedback</em> of a design, there are several principal questions we can ask:</p><ul><li>How do I know what action is possible?</li><li>How do I know what are the steps for certain action?</li><li>How do I know if an action worked?</li></ul><h3>5. Design problem is everywhere</h3><p>Above all, this specialization taught me to see the world differently. We can keep a curious mindset and observe everything around us, from the design of a doorknob to the shape of a soda bottle. Design is everywhere, so are the efficiency and inefficiency that come with it.</p><p>Design requires research, it starts with an ask, an idea, or simply an observation. From a vague, big idea we start to explore and learn. The process itself provides a tremendous joy for any designer.</p><p>Marshall Shen © 2017</p><p><em>Originally published at </em><a href="http://himarsh.org/what-i-learned-from-interaction-design/"><em>himarsh.org</em></a><em> on October 10, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed60ce86b30c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/babystep/5-things-i-learned-from-interaction-design-specialization-on-coursera-ed60ce86b30c">5 things I learned from interaction design specialization on Coursera</a> was originally published in <a href="https://medium.com/babystep">Babystep</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating Vue.js from Asset Pipeline to Webpack]]></title>
            <link>https://medium.com/babystep/migrating-vuejs-from-asset-pipeline-to-webpack-6297621c6195?source=rss----9ae525615af6---4</link>
            <guid isPermaLink="false">https://medium.com/p/6297621c6195</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[webpack]]></category>
            <dc:creator><![CDATA[Kyle Reden]]></dc:creator>
            <pubDate>Tue, 10 Oct 2017 14:48:27 GMT</pubDate>
            <atom:updated>2017-10-10T14:48:27.047Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKGEHtJF3uqNBC7xGKF6Iw.png" /><figcaption>Vue and Webpack and Rails…Oh My!</figcaption></figure><p>Where I work we use a fairly standard <a href="http://rubyonrails.org/">Rails</a> stack. That is to say we use Rails + Javascript (<a href="https://vuejs.org/v2/guide/">Vue.js</a>) + SCSS + HAML to create many of our web platforms. This uses the <a href="http://guides.rubyonrails.org/asset_pipeline.html">Asset Pipeline</a> to preprocess, compile, and minify all of our assets.</p><p>Historically this has also posed a number of challenges, such as:</p><ul><li>Maintenance and versioning of 3rd party libraries.</li><li>Tight coupling to Rails via .erb and .haml files.</li><li>The need to use a lot of global variables in javascript (think window.var).</li><li>Inability to use <a href="https://vuejs.org/v2/guide/single-file-components.html">single file components</a> (.vue) to package our components (template, logic, and styles) into a single concern.</li></ul><p>With all that in mind, we were fairly estatic when it was announced that <a href="https://webpack.github.io/">Webpack</a> and <a href="https://yarnpkg.com/en/">Yarn</a> support would be coming to <a href="http://weblog.rubyonrails.org/2017/4/27/Rails-5-1-final/">Rails 5.1</a> via the <a href="https://github.com/rails/webpacker">Webpacker gem</a>. With this we would be able to:</p><ul><li>Use Yarn to manage 3rd party dependencies.</li><li>Start to migrate to .vue files for our components thanks to Webpacks preprocessors.</li><li>Start to use ES6 module system and migrate away from using global variables.</li><li>Have much greater control over our asset pipeline via webpack loaders.</li></ul><p>We have just started the journey to migrate, and this will be the first in a series of blog posts detailing our path. With that said, let’s begin!</p><p>Note: All of my Javascript examples are going to reference Vue.js since thats what we use.</p><h3>Asset Pipeline vs Webpack: Round One…FIGHT!</h3><p>From <a href="http://guides.rubyonrails.org/asset_pipeline.html">Rails Guides</a>:</p><blockquote><em>The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages and pre-processors such as CoffeeScript, Sass and ERB. It allows assets in your application to be automatically combined with assets from other gems. For example, jquery-rails includes a copy of jquery.js and enables AJAX features in Rails.</em></blockquote><p>From <a href="https://webpack.js.org/concepts/">Webpack concepts</a></p><blockquote><em>webpack is a module bundler for modern JavaScript applications. When webpack processes your application, it recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into a small number of bundles — often only one — to be loaded by the browser.</em></blockquote><p>Those sound pretty similiar and indeed when it comes to compression and minification they pretty much produce the same results. Where asset pipeline falls short and webpack shines is when it comes to working with new things being introduced in the latest versions of javascript and its frameworks. Top of mind are <a href="http://2ality.com/2014/09/es6-modules-final.html#ecmascript-6-modules">ES6 modules</a>, the aforementioned single file components, and loaders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*BE9G4JBWwdS8WcVTCdAUOA.png" /><figcaption>Single File Component</figcaption></figure><p>Single file components allow us to take the template, logic, and styles for a given peice of functionality, or component, in our application and combine them into one file. This collocation makes the component more cohesive and maintainable.</p><p>Modules allow us to export bits of functionality and import them later on when we want them. In many cases this eleminates the need for global declerations, allowing us to be much more selective about what scope things are loaded in.</p><p><a href="https://webpack.js.org/concepts/loaders/">Loaders</a> allow you to preprocess files as you load them. This is what allows us to do things like transform a .vue file into html, js, and css static assets.</p><h3>Plan of attack…</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZvUX4MMUc-bu9ulT.png" /><figcaption>No Bothens where hurt during the making of this blog post.</figcaption></figure><p>The first thing we did was make a plan of attack. We sat down and looked at the state of our front end, and realized that this migration would have to happen in phases as it would be way too costly and unmanageable to do all at once. The phases we decided on were:</p><p>0. Installation and setup.</p><ol><li>Install core libraries and app bootstrapping.</li><li>Get JavaScript tests working.</li><li>Server configuration.</li><li>Core components, app utilities, and installing secondary libraries.</li><li>Secondary componants, mixins and filters</li><li>Global CSS.</li><li>Cleanup of any left over unnecessary things.</li></ol><p>The basic idea here was to break up the work into multiple steps that could be further defined, distilled and completed in managable chunks over time by multiple devs. This lets us spread the knowledge as well as minimize impact on implementation and execution of new features on the project.</p><h3>Phase 0</h3><blockquote>0. Installation and setup.</blockquote><p>You might be thinking “Well duh!” but I like to be thorough. This also allows us sometime in-house to make sure no new dependencies break a currently-functioning app. Things we will need to do:</p><ol><li><a href="https://yarnpkg.com/en/docs/install">Install Yarn</a>. If you are using Homebrew run: brew install yarn which will also install node if you don&#39;t already have it. Alternativly if you are using <a href="https://github.com/creationix/nvm">nvm</a> to manage node you can run brew install yarn --without-node to skip node.</li><li><a href="https://github.com/rails/webpacker#installation">Install the Webpacker Gem</a> by adding it to your Gemfile and running:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/969fc9b740d85d235582d8b295de40d8/href">https://medium.com/media/969fc9b740d85d235582d8b295de40d8/href</a></iframe><p>Let’s take a moment and look at what we have done so far. First, we installed Yarn which is a JavaScript package manager. Yarn is pretty cool because it gives us a quick, secure, and reliable way to install and manage JS packages across the app. Check out the <a href="https://yarnpkg.com/en/docs">docs</a> to read more and familiarize yourself with it.</p><p>Second, we installed the <a href="https://github.com/rails/webpacker">Webpacker gem</a>. This installs <a href="https://webpack.github.io/">Webpack</a> and also does a few other things of note. First you will notice that it created a file called config/webpacker.yml. This is what tells webpack how to configure itself. If you take a gander in this file you will see</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eec32d1d04257ec09848eb35a2e1cd89/href">https://medium.com/media/eec32d1d04257ec09848eb35a2e1cd89/href</a></iframe><ul><li>source_path is going to tell Webpack which directory it should start in. Notice that by default, it starts at app/javascript which is different from Rails&#39;s typical app/assets/javascripts. This is better to help define what webpack will handle vs asset pipeline.</li><li>source_entry_path is where Webpack looks for its entry points for the app.</li><li>public_output_path we will also have a new folder called public/packs. This is where webpack will deposit files once it has finished bundling all the assets together.</li></ul><p>Feel free to change any of these values for your specific needs — I just left them default for now. Everything else in the file is pretty standard setup stuff and should be customized accordingly. Also head over to the <a href="https://github.com/rails/webpacker/tree/master/docs">docs</a> to learn more.</p><p>You will also notice that we have a new <a href="https://github.com/rails/webpacker/blob/master/docs/folder-structure.md">folder structure</a> under app/javascript/packs. As noted earlier, everything in here Webpack will add to its dependency graph, run through any relvent loaders and plugins and then deposit the results in public/packs. Right now there is just a file called application.js in there but we will add to it shortly.</p><p>The last thing I want to point out is a new file called yarn.lock in the root of the project. Think of this file like you do the Gemfile.lock. In fact, it&#39;s the same thing for javascript. This is one of the beautiful things about Yarn: it lets us lock our JS dependencies versions just like you would a gem!</p><h3>Phase 1</h3><h4>Install Core Libraries — Pt. 1</h4><blockquote>1. Install Core libraries and app bootstrapping.</blockquote><p>When I say Install Core libraries, I mean any JS library that is required for your application to function properly. Since we are a Vue app for us that means:</p><ol><li>Vue</li><li>Vuex</li><li>VueRouter</li></ol><p>You might be saying to yourself, “There is no way that’s all the JS libraries you’re using in your app…” and you would be correct! We certainly use jQuery, lodash, and others that we are going to keep in the Asset Pipeline for now. Remember, baby steps… 😃</p><p>Now, let’s get to it. First, we are going to install our framework via the rails webpacker command. Webpack comes with several <a href="https://github.com/rails/webpacker#integrations">integrations</a> for React, Angular, Vue and Elm. Since I am using Vue I ran:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/314cd536bd6d1b269466e521bf99f36b/href">https://medium.com/media/314cd536bd6d1b269466e521bf99f36b/href</a></iframe><p>From the <a href="https://github.com/rails/webpacker#integrations">documentation</a> this command</p><blockquote><em>… will add Vue and required libraries using yarn plus any changes to the configuration files. An example component will also be added to your project in app/javascript so that you can experiment with Vue right away.</em></blockquote><p>After that run yarn to get the rest of what we need.</p><p><em>Tip: If you are unsure what the name of a package might be you can always head over to </em><a href="https://yarnpkg.com/en/packages"><em>Yarn’s package search</em></a><em> to look stuff up!</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebb672ff6915f7189b1e29087acd4ceb/href">https://medium.com/media/ebb672ff6915f7189b1e29087acd4ceb/href</a></iframe><p>Sweet! Now if we look in app/javascript we should see a directory structure like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae02b481959767b2bfaefe6d9cfcf265/href">https://medium.com/media/ae02b481959767b2bfaefe6d9cfcf265/href</a></iframe><p>I am going to skip over application.js and app.vue right now and focus on hello_vue.js because it has things in it that are going to be important to us.</p><h4>App bootstrapping — Pt. 1</h4><p>If you crack open hello_vue.js you will be greated by:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fae9790165d767142484aea24342914/href">https://medium.com/media/3fae9790165d767142484aea24342914/href</a></iframe><p>That first chunk at the top is a great way to test out that things are working properly. First, pop open wherever you are loading head (ours is in a file aptly named head) and add</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*wuTDAoctLEnUQUu4CbuzyQ.png" /></figure><p>to it. Once that&#39;s done, go and launch your dev server and you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B1PA-RADEtTlfoK9.png" /></figure><p>appended to the bottom of your app. Opening up app.vue and adding a background color, like purple, to the styles and refreshing the page should yield:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/0*TpTNkrDv1B_UI72Y.png" /></figure><p>Dope! Webpack is working properly! Now, all thats happening here is that we are creating, mounting, and appending a new Vue app to the end of the page. As the comment says though, we wont be able to target elements in our already existing app. This isn’t very useful to us. Reading further though we see that there is a different way to do things; a way that lets us interact with our current app! Let’s check it out.</p><p>Lets just get rid of that top portion — we don’t need it. Actually, we will only want to keep the lines starting at import Vue from &#39;vue/dist/vue.esm&#39; to the bottom of the file. When you are done, things should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4369d15acbd5e4f9f650f40ac98b91ea/href">https://medium.com/media/4369d15acbd5e4f9f650f40ac98b91ea/href</a></iframe><p>Now if we load up our app we should see…nothing. Hello Vue is gone and checking the console we see an error [Vue warn]: Cannot find element: #hello. This makes sense, since we are no longer appending the app to the end of the document. Go ahead and add:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c55b06aad51d115f182b075be4de1817/href">https://medium.com/media/c55b06aad51d115f182b075be4de1817/href</a></iframe><p>on the landing page of your app and refresh. Oh look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vs2xdz8a3zrDhTEZ.png" /></figure><p><em>A quick note here: Remember that we added </em><em>&lt;%= javascript_pack_tag &#39;hello_vue&#39; %&gt; to the head of the project. At this point you will want to make sure this loads AFTER asset pipeline so we can find the apps elements.</em></p><p><em>For us that meant placing that line in our footer under </em><em>= javascript_include_tag “application-foot” which is where we load in all our asset pipeline stuff.</em></p><p>Good stuff! But we still have a problem…while we are certainly targeting an element in our application to mount the Vue app too, we now have two apps running. If you have the Vue browser tools you can open it up to see the evidence of this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/0*9O4jzOXke1H92Mk0.png" /></figure><p>To fix this we need to do a couple of things.</p><h4>App bootstrapping — Pt. 2</h4><p>First lets do some cleanup and renaming.</p><ul><li>In app/javascript/packs we can get rid of application.js. We wont need it.</li><li>Rename hello_vue.js to main.js (Remember to change the javascript_pack_tag and stylesheet_pack_tag too!). This is going to become the new place we will bootstrap the current app.</li><li>Head back to where you placed the hello div and remove it.</li></ul><p>Finally lets make a new folder app/javascript/src/components and place app.vue(updating the import in main.js accordingly) in it. Our new structure looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb3f3d2180ca7d58fd6c5b4775f68aff/href">https://medium.com/media/cb3f3d2180ca7d58fd6c5b4775f68aff/href</a></iframe><p>Now lets tackle the next step: migrating our actual app! Open up whatever file you do this in currently (for us it’s app/assets/javascripts/main.js.erb). Take the part where you bootstrap the new app (Vue: new Vue({})) and move it to our new main.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07300b2d163de47ada5a5c25df900176/href">https://medium.com/media/07300b2d163de47ada5a5c25df900176/href</a></iframe><p>Next lets migrate over the store and router. Add app/javascript/src/store/index.js. Using the <a href="https://webpack.js.org/concepts/modules/">module system</a> we are going to export a function that builds our store.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/771bb5b0e720f45207db72f6a2a85890/href">https://medium.com/media/771bb5b0e720f45207db72f6a2a85890/href</a></iframe><p>For the router we are going to do the same thing. Add app/javascript/src/router/index.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a1d6fa2374bad0bd96b5a14c3bfbf68/href">https://medium.com/media/0a1d6fa2374bad0bd96b5a14c3bfbf68/href</a></iframe><p>Notice the global window.app. This is a hold over from the way we used to do things. By making sure the asset pipeline files are loaded first I don&#39;t have to make huge changes to the current architecture of the app to migrate this over yet.</p><p>In app/javascript/packs/main.js import the router and store</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5759ead4ac2cb5e4c8a09dd21cf9333b/href">https://medium.com/media/5759ead4ac2cb5e4c8a09dd21cf9333b/href</a></iframe><p>Almost done, just a few things left to do. Next, we are going to want to clean up the requires for Vue and pals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/0*zlQnIc3-EGqtpSzq.png" /></figure><p>Oh bother…We will also need to tackle any dependencies like vue-multiselect. Yarn + imports to the rescue!</p><pre>yarn add vue-multiselect</pre><p>This is what it should look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54acff36d1071cce25c72edbbc658b43/href">https://medium.com/media/54acff36d1071cce25c72edbbc658b43/href</a></iframe><p>We also declare some global components, filters, and mixins in main.js.erb and run some other setup tasks that I am going to move over too making this new main.js the one place we do all of our setup. By the end we will have something that looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c56bb123ee15a891679b3377e90b555c/href">https://medium.com/media/c56bb123ee15a891679b3377e90b555c/href</a></iframe><p>And finally lets change app.vue. I&#39;ll rename it to example.vue and edit its contents like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c163d9c29420357fcd711b7587a88f5f/href">https://medium.com/media/c163d9c29420357fcd711b7587a88f5f/href</a></iframe><p>Once that’s done we add it to main.js like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a4e3f9b615b4910e678cdae4a8a01bf/href">https://medium.com/media/1a4e3f9b615b4910e678cdae4a8a01bf/href</a></iframe><p>And this will prove that the old world and the new world are working together. I added a property to the store called exampleText = &quot;Asset Pipeline + Webpack == Win!&quot; which we are accessing from this component.</p><p>Reload the app and voilà:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OpKu5z3lM_oDcviu.png" /></figure><p>And that’s pretty much all there is to it. Now we have an app that is running both Asset Pipeline and Webpack. We are serving up the core bits of the app via Webpack and letting AP handle the rest and have a .vue templated component rendering inside the app. This means that moving forward, work can begin on the rest of the phases.</p><p>You’re probably wondering…what about tests? We are still working on that part and will have something out about it soon. In the mean time check out the <a href="https://github.com/rails/webpacker/blob/master/docs/testing.md">testing docs</a>.</p><p>There is also still a lot of work to get everything else up and running to stay tuned as we detail a journey to this new frontier!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6297621c6195" width="1" height="1" alt=""><hr><p><a href="https://medium.com/babystep/migrating-vuejs-from-asset-pipeline-to-webpack-6297621c6195">Migrating Vue.js from Asset Pipeline to Webpack</a> was originally published in <a href="https://medium.com/babystep">Babystep</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced animation in Vue.js]]></title>
            <link>https://medium.com/babystep/vuejs-animations-javascript-md-fa496111d200?source=rss----9ae525615af6---4</link>
            <guid isPermaLink="false">https://medium.com/p/fa496111d200</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Jason Buss]]></dc:creator>
            <pubDate>Mon, 18 Sep 2017 03:54:32 GMT</pubDate>
            <atom:updated>2017-09-18T03:56:20.259Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUKSUGYM1lQz8TTp1sNHtQ.png" /></figure><p>This is the second part to <a href="https://github.com/babystep-io/vuejs-animations">Baby Steps Vuejs Animations Tutorial</a>. In this tutorial we will learn about creating functional and reusable vuejs transitions using javascript. To follow along you can find the repo here: <a href="https://github.com/babystep-io/vuejs-animations-javascript">Baby Steps Vuejs Animations Javascript</a>.</p><p>You can find the demo in <a href="http://babystep.io/animations/"><strong>here</strong></a>.</p><p>This app is a simple illustration of the two types of transitions we learned in the previous tutorial — single element transitions and group transitions. The base state of this app contains two components, single-transition.js and group-transition.js. These components contain simple CSS fade transitions. We will go through the steps to convert these to javascript transitions!</p><h3>Basics</h3><p>In the previous tutorial we learned how to create transitions using the CSS hooks that the vuejs transition component provided us. These included:</p><ul><li>v-enter - starting state for enter</li><li>v-enter-active - active state for enter</li><li>v-enter-to - ending state for enter</li><li>v-leave - starting state for leave</li><li>v-leave-active - active state for leave</li><li>v-leave-to - ending state for leave</li></ul><p>Similar to the CSS hooks, the transition component also provides javascript hooks:</p><ul><li>v-on:before-enter</li><li>v-on:enter</li><li>v-on:after-enter</li><li>v-on:enter-cancelled</li><li>v-on:before-leave</li><li>v-on:leave</li><li>v-on:after-leave</li><li>v-on:leave-cancelled</li></ul><p>Let’s take a second to understand what these mean exactly. Let’s take a look at v-on:before-enter. There are two key things happening here:</p><p>v-on is a <a href="https://vuejs.org/v2/guide/syntax.html#Directives">directive</a>, and its job is to listen to the DOM for events. before-enter is the event that it is listening for! So, the take away here is that the transition component emits certain events when it is activated, these being before-enter, enter, after-enter, etc... and we can use the v-on directive to listen for these events, and trigger methods in the component when they occur.</p><p>But what about the CSS hooks? If we are creating a javascript only transition, we wouldn’t want the transition component to also apply CSS hooks to the DOM element. That leaves the possibility for CSS rules to interfere with the transition. To solve this, we can use v-bind:css=“false” to tell Vue it can skip the CSS detection.</p><p>With this in mind, let’s jump into our app and see how these things work!</p><h3>Step-1 First Javascript Transition</h3><p>Let’s start with our single-transition component, and convert the CSS fade transition to a javascript one. First, we should tell Vue that we are going to be creating a purely javascript transition by adding the binded css value.</p><pre>... <br>&lt;transition <br>  name=&quot;fade&quot; <br>  v-bind:css=&quot;false&quot;<br>&gt;<br>  &lt;div v-if=&quot;showText&quot; class=&quot;text&quot;&gt;Bob&#39;s Burgers&lt;/div&gt;<br>&lt;/transition&gt;<br>... </pre><pre>&lt;!-- single-transition.js --&gt;</pre><p>This, as we know, will tell Vue to skip the CSS hooks.</p><p>So how should we create this fade effect? Taking a look at the CSS we used to create the fade transition, we can see there were two parts:</p><ol><li>the end state opacity: 0</li><li>the active state transition: opacity 1s</li></ol><p>So similarly, we know that on transition enter (v-on:enter) and on transition leave (v-on:leave) we will have to tell our element to go from no opacity to full and vice versa. There are many ways to implement transitions using javascript.</p><p>Plain Javascript:</p><pre>function fadeOut(el){<br>  el.style.opacity = 1<br>  (function fade() {<br>    if ((el.style.opacity -= .05) &lt; 0) {<br>      el.style.display = &quot;none&quot; <br>      // done!<br>    } else {<br>      requestAnimationFrame(fade);<br>    }<br>  })()<br>}</pre><p>jQuery:</p><pre>$(el).fadeOut(&quot;slow&quot;, () =&gt; {<br>  // done!<br>})</pre><p>Velocity:</p><pre>Velocity(el, &quot;fadeOut&quot;, { complete: () =&gt; {<br>  // done! <br>}})</pre><p>Any of these methods will work, but I prefer to use <a href="http://velocityjs.org/">Velocity</a>. It uses the same api as jQuery’s $.animate(), but is much faster. So for this tutorial we will be creating our animation effects with Velocity.</p><p>So let’s wire up some transitions! Let’s create our fade in and fade out methods. To mirror the Vuejs transition api, we will name them enter and leave.</p><pre>...<br>enter(el, done) {<br>  Velocity(el, &quot;fadeIn&quot;, done)<br>}, <br>leave(el, done) {<br>  Velocity(el, &quot;fadeOut&quot;, done)<br>}<br>...</pre><pre>// single-transition.js</pre><p>Some things to note here. In order to execute this transition, we need to tell Velocity what element to perform the animation on. When the transition component emits the enter event, it passes two arguments along:</p><ol><li>The first being the element that is in transition.</li><li>The second is the done callback</li></ol><p><em>Note that the done callback is only used in the </em><em>enter and </em><em>leave hooks. If they are not used, they will be called synchronously and the transition will finish immediately.</em></p><p>Gotchas aside, see how easy it is to create fade transitions! We still need to do one more thing though, and that’s to tell Vue to execute our enter method on the enter hook.</p><pre>...<br>&lt;transition<br>  name=&quot;fade&quot;<br>  v-bind:css=&quot;false&quot;<br>  v-on:enter=&quot;enter&quot;<br>  v-on:leave=&quot;leave&quot;<br>&gt;<br>  &lt;div v-if=&quot;showText&quot; class=&quot;text&quot;&gt;Bob&#39;s Burgers&lt;/div&gt;<br>&lt;/transition&gt;<br>...</pre><pre>&lt;!-- single-transition.js --&gt;</pre><p>There ya have it! A fully function fade transition using javascript.</p><h3>Step-2 Group Transitions Using Javascript</h3><p>Now that we have converted our fade transition to a pure JS one, let’s see how we can do the same thing for our group-transition.</p><p>We are going to create a horizontal slide transition. There are many ways to achieve this, but one simple way is just to animate the margin of the element. Of course this might not work as intended if the DOM element already has some sort of margin applied to it, but in our case it’ll do just fine! We can explore some other ways to achieve similar affects later. To achieve this affect we know we will need to set some intial margin, and then animate from that state to no margin.</p><p>So first things first, let’s create our methods.</p><pre>...<br>beforeEnter(el) {<br>  el.style.marginLeft = &#39;10px&#39;<br>  el.style.opacity = 0<br>},</pre><pre>beforeLeave(el) {<br>  el.style.position = &#39;absolute&#39;<br>},</pre><pre>enter(el, done) {<br>  Velocity(el, {marginLeft: 0, opacity: 1}, done)<br>},</pre><pre>leave(el, done) {<br>  Velocity(el, {marginLeft: &#39;10px&#39;, opacity: 0}, done)<br>}, <br>... </pre><pre>// group-transition.js</pre><p>Here we are defining four methods beforeEnter, beforeLeave, enter, and leave. beforeEnter is useful for setting up the initial state of the transition. We know that it is hidden (opacity = 0), and that it is pushed over to the right (marginLeft = &#39;10px&#39;). On enter we will be animating both of these properties to their shown states, and on leave we will animate them back! The last method beforeLeave simply sets the position style attribute to &#39;absolute&#39; so that it is removed from the flow of the list and the other elements can slide gracefully to their new positions in the list.</p><p><em>One limitation to creating transitions using javascript is that there is no hook for </em><em>v-move. We used this in our CSS transitions for animating effects like shuffling the list, and for sliding elements to their new places when an item was removed. Until the api is updated, we must maintain this effect with a CSS hook.</em></p><p>The final step here is to wire up these methods to the transition component!</p><pre>... <br>&lt;transition-group <br>  name=&quot;list&quot; <br>  v-bind:css=&quot;false&quot; <br>  v-on:before-enter=&quot;beforeEnter&quot; <br>  v-on:before-leave=&quot;beforeLeave&quot; <br>  v-on:enter=&quot;enter&quot; <br>  v-on:leave=&quot;leave&quot; <br>&gt; <br>  &lt;div v-for=&quot;item in items&quot; v-bind:key=&quot;item.id&quot; class=&quot;item&quot;&gt; <br>    &lt;p class=&quot;item-text&quot;&gt;id: {{ item.id }}&lt;/p&gt; <br>    &lt;p class=&quot;item-text&quot;&gt;text: {{ item.text }}&lt;/p&gt; <br>  &lt;/div&gt; <br>&lt;/transition-group&gt; <br>... </pre><pre>&lt;!-- group-transition.js --&gt;</pre><p>That’s all there is to it! Now you have successfully created group transitions using javascript.</p><h3>Step-3 Functional &amp; Reusable Javascript Components</h3><p>One problem with creating transitions this way is that we are adding methods to our components that don’t really have anything to do with their functionality. This is not a big deal in smaller components, but you can imagine that as your components get more complex, these methods would clutter up the business logic. To remedy this, we can abstract our transitions to their own components! Let’s do that now starting with the single fade transition.</p><p>Let’s create a file called fade-transition.js</p><p>This component will have all of the same methods that we used in our single-transition component, but will look a little different to all of the components we&#39;ve written so far. We will write our fade-transition as a functional component.</p><p>Why <a href="https://vuejs.org/v2/guide/render-function.html#Functional-Components">functional components</a>? Functional components are stateless (no data attribute) and instanceless (no lifecycle hooks) components. They are really just functions that take some props. If you think about our transition, this is pretty much exactly what it does — performs actions on child elements based on events.</p><p>There is a lot of information about functional components to distill. Since our fade-transition.js component is fairly small, let&#39;s look at it in its entirety and then zero in on the important parts.</p><pre>((() =&gt; { <br>  Vue.component(&quot;fade-transition&quot;, { <br>    functional: true, <br>    render: (createElement, context) =&gt; { <br>      let data = { <br>        props: { <br>          name: &quot;fade&quot;, <br>          css: false <br>        }, <br>        on: { <br>          enter(el, done) { <br>            Velocity(el, &quot;fadeIn&quot;, done) <br>          }, <br><br>          leave(el, done) { <br>            Velocity(el, &quot;fadeOut&quot;, done) <br>          } <br>        }, <br>      } <br>      return createElement(&#39;transition&#39;, data, context.children) <br>    } <br>  }) <br>}))() </pre><pre>// fade-transition.js</pre><ul><li>The first thing to note is the function: true - this as you probably guessed denotes this as a functional component!</li><li>The next big change from the components we’re used to seeing is the <a href="https://vuejs.org/v2/guide/render-function.html">render function</a>. Usually we use a template declaration for passing HTML markup to our component.</li></ul><p>The render function is just another way of defining the HTML and will alow us the full power of JavaScript!</p><p>The render component takes some arguments, the first one being the createElement function. createElement basically returns a description for Vue on how to render the Virtual DOM element. You can see the last return of our component is createElement(&#39;transition&#39;, data, context.children). createElement accepts 3 arguments:</p><ol><li>The first is an HTML tag name.</li><li>The next is a data object that details the attributes you would use in the template.</li><li>The last is children Virtual Nodes.</li></ol><p>You can learn more about the data object <a href="https://vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth">here</a></p><p>For this component though we are mainly concern with defining the behavior of the events triggered by the v-on directive, giving our component a name, and defining the css behavior. We do this in a data object, defining the key of props and its value, and the key of on and its value.</p><p>That’s the basics of functional components!</p><h3>Step-4 Dynamic Components</h3><p>One last important concept is Dynamic Components. Let’s say we have an image slider component that has arrows on the left and right sides. When someone clicks the right arrow, the current image slides to the left with a new image from the right sliding into view, and vice versa for clicking the left arrow. How would we be able to achieve this type of transition? Up until now we have explicitly defined the behavior of our transitions. It can either slide up, down, left, right, etc… but is not equipped to perform some or all based on some data.</p><p>One solution might be to define the transition’s method behaviors based on some property, and pass that data to the transition component.</p><pre>... <br>&lt;slide-transition :direction=&quot;left&quot;&gt; <br>  &lt;div v-if=&quot;showText&quot; class=&quot;text&quot;&gt;Bob&#39;s Burgers&lt;/div&gt; <br>&lt;/slide-transition&gt; <br>...</pre><pre>... <br>Vue.component(&quot;slide-transition&quot;, { <br>  functional: true, <br>  props: [&quot;direction&quot;], <br>  render: (createElement, context) =&gt; { <br>...</pre><p>In the on: portion of the data object, you can then use a conditional to switch behavior based on the value of the prop.</p><p>However another solution that might be cleaner is to use Dynamic Components. This just dynamically changes between componets at one mount point. To do this we use the &lt;component&gt; element and bind the value of the component to the is attribute. Simple as that!</p><pre>... <br>&lt;component :is=&quot;transitionType&quot;&gt; <br>  &lt;div v-if=&quot;showText&quot; class=&quot;text&quot;&gt;Bob&#39;s Burgers&lt;/div&gt; <br>&lt;/component&gt; <br>... </pre><pre>data() { <br>  return { <br>    transitionType: &quot;fade-transition&quot;, <br>    showText: true <br>  } <br>}, <br>... </pre><pre>// single-transition.js</pre><p>Here is the example in our single-transition component. We declare a dynamic component and bind its value to a data attribute called transitionType. In this way we can change transitionType on the fly, and as long as we have a transition with that name defined, that transition component will be used at the at the mount point of the component.</p><p>Now we can define as many different transition types we want, and change them as we see fit! In this app, we bind transitionType to a select box, the options being names of various transition components. Open the finished_app and change the value of the select box to see some example transitions. These are some example ideas for transitions.</p><h3>Bonus</h3><p>One interesting hack to note in the finished_app is text-change-transition.js. In this component we want to change the value of the innerText in one javascript hook, and change it back to its original value. One way would be to use a prop, but what if we don&#39;t want the transition to be dependant on a prop from the parent component. The hack seen here is to declare a domProps object in which to store this value, and use a reference to this inside the createElement function to reference it.</p><pre>... <br>render: (createElement, context) =&gt; { <br>  let self = this <br>  let data = { <br>    props: { <br>      name: &quot;text-change&quot;, <br>      css: false <br>    }, <br>    domProps: { <br>      text: &quot;&quot; <br>    }, <br>    on: { <br>      beforeEnter(el) { <br>        self.text = el.innerText <br>        el.innerText = &quot;Time for the charm bomb to explode.&quot; <br>      }, </pre><pre>      enter(el, done) { <br>        Velocity(el, &quot;fadeIn&quot;, {duration: 500, complete: () =&gt; { <br>          Velocity(el, &quot;fadeOut&quot;, {duration: 250, complete: () =&gt; { <br>            el.innerText = self.text <br>            Velocity(el, &quot;fadeIn&quot;, {duration: 500, complete: done}) <br>          }}) <br>        }}) <br>       }, <br>... </pre><pre>// text-change-transition.js</pre><p>Something to keep in mind if you ever need a quick and easy way to keep track of some value in between javascript hooks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa496111d200" width="1" height="1" alt=""><hr><p><a href="https://medium.com/babystep/vuejs-animations-javascript-md-fa496111d200">Advanced animation in Vue.js</a> was originally published in <a href="https://medium.com/babystep">Babystep</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing with Vue.js]]></title>
            <link>https://medium.com/babystep/testing-with-vue-js-373dba84f1c3?source=rss----9ae525615af6---4</link>
            <guid isPermaLink="false">https://medium.com/p/373dba84f1c3</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuex]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Marshall Shen]]></dc:creator>
            <pubDate>Thu, 31 Aug 2017 19:53:10 GMT</pubDate>
            <atom:updated>2017-08-31T19:52:58.806Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Lk5N_BR7f9p1SE97mgBWJg.png" /></figure><p>For the past year I have been on the team building progressive web application (PWA) using <a href="http://vuejs.org/">Vue.js</a>. The framework is relatively new, so there is not a standard guideline on how to properly test a large scaled Vue application.</p><p>If you are building a large PWA with Vue.js as the frontend framework, I hope you find this blogpost useful. In this post I will share some of our learning lessons and pragmatical guidelines our team come up in tesing with Vue.js.</p><h3>Challenge of scaling</h3><p>It all starts with the growing pain. As we keep adding components to our front end app, we realize that we need to adopt <a href="https://facebook.github.io/flux/">flux architecture</a> and introduce <em>Vuex</em> to scale. As we adopt <em>Vuex</em> and add more pages to the app, we realize that we need to introduce <em>Vue Router</em> to handle more sophisticated rendering. Very soon, our front end has odd behaviors, our QA start to get confused, and developers start to scream at each other — okay, maybe not scream, but we were definitely frustrated bunch.</p><p>Then comes the natural conversation of <strong>improve code quality</strong>, which leads to the conversation of <strong>add test coverage to our frontend</strong>. So the developers rolled up our sleeves and start to tackle of the problem of writing Javascript tests against a fairly large PWA in Vue. Experiments after another, code review after another, we came up with our solution, yet two thoughts stand true in our discovery, one good, one bad.</p><h3>The bad: tooling of Javascript testing</h3><p>First, let’s start with the bad. Regardless of which Javascript framework we use, when it comes to front end testing, there are many ala carte solutions out there, each may solve one aspect of testing very well, but none excel in all aspects of testing. Before we start building our own Javascript testing procedure, we come up with a checklist of what functionality we want when running the tests. Below is a list and what we settled on.</p><p><strong><em>Package manager</em></strong>: <a href="https://webpack.github.io/">Webpack</a>, <a href="https://yarnpkg.com/en/">Yarn</a>, and <a href="http://guides.rubyonrails.org/asset_pipeline.html">Rails asset pipeline</a></p><p><strong><em>Test runner</em></strong>: <a href="https://karma-runner.github.io/1.0/index.html">Karma</a></p><p><strong><em>Assertion</em></strong>: <a href="http://chaijs.com/">Chai.js</a></p><p><strong><em>Mocks and stubs</em></strong>: <a href="http://sinonjs.org/">Sinon.js</a></p><p>The testing solution we come up feels piece-meal, which reflects the fragmented nature of Javascript testing framework. Within Vue.js community people have been working on Vue specific testing framework such as <a href="https://github.com/vuejs/vue-test-utils">Vue test utils</a>, but as of the time of this writing, the project is fairly young.</p><p>A sample test inside the app looks like below, the describe and it blocks are provided by <strong>Karma.js</strong>. The expect clause is provided by <strong>Chai.js</strong>. Note that this piece-meal solution should also apply to other frameworks such as <a href="https://angularjs.org/">Angular</a> and <a href="https://facebook.github.io/react/">React</a>.</p><pre>describe(&quot;formatDates&quot;, () =&gt; <br>  { <br>    const app = window.app <br>    const expect = window.chai.expect <br>    const subject = window.app.mixins.formatDates <br>    const moment = window.moment </pre><pre>    describe(&quot;#formatDate&quot;, () =&gt; { <br>      it(&quot;returns a date formatted as MM.DD.YYYY&quot;, () =&gt; { <br>        const date = moment().format() <br>        const formattedDate = moment.utc(date).format(&quot;MM.DD.YYYY&quot;)   </pre><pre>        expect(subject.methods.formatDate(date))<br>         .to.eq(formattedDate)  <br>      }) <br>    }) <br>  <br>   describe(&quot;#formatUtcDate&quot;, () =&gt; { <br>     it(&quot;returns an utc formatted date&quot;, () =&gt; { <br>       let startDate = moment().format() <br>       let value = subject.methods.formatUtcDate(startDate) <br>       let formattedDate = moment.utc(startDate).format()<br>       <br>       expect(value).to.eql(formattedDate) <br>     }) <br>   }) <br>})</pre><h3>The Good: component tests and interaction tests</h3><p>Okay, let’s go into the good thought. We realize that <strong>component-based framework allows us to test our Javascript code differently</strong>. Traditionally, we write unit test, integration test and end to end test around Javascript application. Although those scopes of test might still hold true while testing with Vue, we like to think that we can write two types of tests with Vue.js: <strong>component tests</strong> and <strong>interaction tests</strong>.</p><p>At its core, a Vue app is composed of <strong>components and their interactions</strong>, and the ideas below hold true for each component:</p><ol><li>each component owns its view</li><li>each component gets its data locally (props) or globally (Vuex)</li><li>each component handles events by emitting events, or updating local or global data</li></ol><p>In a large scale web application, Vue.js follows <a href="https://facebook.github.io/flux/">flux architecture</a> with core plugin <a href="https://github.com/vuejs/vuex">Vuex</a> to handle state management, and our tests should leverage the design of flux architecture.</p><h3>Component tests</h3><p>Component tests focus on functionality of a component, which is similar to unit tests. Specifically, we want to verify that:</p><ol><li><strong>Data</strong>. A component has correct data, computed property, props loaded at a given life cycle. This may require correct setup of Vuex store, and also the calling of correct lifecylce method such as mount.</li><li><strong>Events</strong>. A component can properly handle different events by either <strong>emitting events</strong> or <strong>change data</strong>. This may require correct setup of Vuex store, and properly stubs and spys of event listeners.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*PEDxlTUorqNjU_Wu.png" /></figure><p>Below is an example of verifying the correct of data.</p><pre>describe(&quot;Account Setting Component&quot;, () =&gt; { <br>  const Vue = window.Vue <br>  const Vuex = window.Vuex <br>  const AccountSettingComponent = window.app.components.AccountSetting <br>  const store = new Vuex.Store({ <br>    state: { <br>      account: { settings: { display_settings: true } } <br>     } <br>  }) </pre><pre>  let vm</pre><pre>  beforeEach(() =&gt; { <br>    const Ctor = Vue.extend(AccountSettingComponent) <br>    vm = new Ctor({ <br>      template: &quot;&lt;div id=&#39;vue-account-settings-component&#39;&gt;&lt;/div&gt;&quot;,<br>      propsData: {}, <br>      store: store <br>    }) <br>    vm.$mount() <br>   }) </pre><pre>   describe(&quot;#mounted()&quot;, () =&gt; { <br>     it(&quot;fetches display settings from the store&quot;, () =&gt; { <br>       expect(vm.displaySettings).to.equal(true) <br>     }) <br>   }) <br>})</pre><p>At the beginning of the test, we explictly require dependencies around <strong>Vue</strong>, including the Vue, Vuex and the component that we try to render. In addition, we set up <strong>const store</strong> with a JSON object, which we only mock the minimum amount of data (i.e. state) that is required within the test.</p><p>Inside beforeEach() block we call the constructor of the component by using Vue.extend, and AccountSettingComponent is nothing but a JSON object, a more detailed doc is <a href="https://012.vuejs.org/api/options.html#name">here</a>. In the end, we can $mount() so that the we “activate” the component.</p><p>Let’s say we want to check the correctness of event handling, we have a method called handleDisplaySettingToggle that toggles display_setting on and off, we can fire off the event from the component and verify it from data.</p><pre>describe(&quot;Account Setting Component&quot;, () =&gt; { <br>  const Vue = window.Vue <br>  const Vuex = window.Vuex <br>  const AccountSettingComponent = window.app.components.AccountSetting <br>  const store = window.app.store </pre><pre>  let vm </pre><pre>  beforeEach(() =&gt; { <br>    const Ctor = Vue.extend(AccountSettingComponent) <br>    vm = new Ctor({ <br>      template: &quot;&lt;div id=&#39;vue-account-settings-component&#39;&gt;&lt;/div&gt;&quot;, <br>      propsData: {}, <br>      store: store <br>    }) </pre><pre>    vm.$mount() <br>  }) <br>  ... </pre><pre> describe(&quot;#methods&quot;, () =&gt; {  <br>   describe(&quot;handleDisplaySettingsToggle&quot;, () =&gt; { <br>     it(&quot;toggles display settings&quot;, () =&gt; { <br>       vm.handleDisplaySettingsToggle(false) <br>       expect(vm.displaySettings).to.eql(false) <br>     }) <br>    }) <br>  }) <br>})</pre><h3>Interaction tests</h3><p>Interaction tests focus on interactions between components, router and store. This is close to integration test. Specifically, we can verify that:</p><ol><li><strong>State change</strong>. An event inside one component dispatches actions to other components or store, resulting state change in other components.</li><li><strong>Server client side interaction</strong>. An action dispatched triggers an ajax with specific parameters. Upon receiving expected response from the server, which we can stub out, then the app renders correct data on the view.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*i6N2NAhNWdcEcE_K.png" /></figure><pre>describe(&quot;Interaction tests: account settings and account review&quot;, () =&gt; { <br>  const Vue = window.Vue <br>  const Vuex = window.Vuex <br>  const AccountSettingComponent = window.app.components.AccountSetting <br>  const AccountReviewComponent = window.app.components.AccountReview <br>  let vm </pre><pre>  const store = new Vuex.Store({ <br>    state: { <br>     account: { settings: { display_settings: true } } <br>    } <br>  }) </pre><pre>  beforeEach(() =&gt; { <br>    const Ctor1 = Vue.extend(AccountSettingComponent) <br>    vm1 = new Ctor1({ <br>      template: &quot;&lt;div id=&#39;vue-account-settings-component&#39;&gt;&lt;/div&gt;&quot;,   <br>      propsData: {}, <br>      store: store <br>    }) </pre><pre>   vm1.$mount() </pre><pre>   const Ctor2 = Vue.extend(AccountReviewComponent) <br>   vm2 = new Ctor2({ <br>     template: &quot;&lt;div id=&#39;vue-account-review-component&#39;&gt;&lt;/div&gt;&quot;, <br>     propsData: {}, <br>     store: store <br>   }) <br>   <br>   vm2.$mount() }) <br>   ... </pre><pre>   describe(&quot;display_seetings&quot;, () =&gt; { <br>     it(&quot;toggles display settings&quot;, () =&gt; { <br>       vm1.handleDisplaySettingsToggle(false)<br>       expect(vm2.displaySettings).to.eql(false) <br>     }) <br>   }) <br>})</pre><p>The key for the interaction test is that both vm1 and vm2 share the same store so that the state change go through the same store.</p><p>Note that neither <strong>component tests nor interaction tests verifies what is actually rendered on the DOM</strong>. This is the beauty of component-based framework: if a component is populated with correct data and handles events the right way, the view should take care of itself.</p><p>Marshall Shen © 2017</p><p><em>Originally published at </em><a href="http://himarsh.org/testing-with-vuejs/"><em>himarsh.org</em></a><em> on August 28, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=373dba84f1c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/babystep/testing-with-vue-js-373dba84f1c3">Testing with Vue.js</a> was originally published in <a href="https://medium.com/babystep">Babystep</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue.js Transitions]]></title>
            <link>https://medium.com/babystep/vuejs-transitions-3842d8b633ae?source=rss----9ae525615af6---4</link>
            <guid isPermaLink="false">https://medium.com/p/3842d8b633ae</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[Jason Buss]]></dc:creator>
            <pubDate>Tue, 29 Aug 2017 14:58:41 GMT</pubDate>
            <atom:updated>2017-09-18T03:55:11.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cG2lMSk1nBbKPX-1hCNHTg.png" /></figure><p><a href="https://github.com/babystep-io/vuejs-animations">babystep-io/vuejs-animations</a></p><p>You can find the demo <a href="http://babystep.io/todos/"><strong>here</strong></a>.</p><p>If you would like to code along, clone this repo and open the index.html. The root contains a todo list project scaffold with no transitions or animations that you will add to in each of these steps! For the finished version you can also look in the finished_app/ folder. This folder mirrors the folder structure of the root app but has all of the transitions in place.</p><h3>Why Transitions?</h3><p>Transitions and animations are a very important design tool. They have many uses — some important ones being: the ability to influence or focus user action, make content more readable, and make designs more kinetic and engaging. One of my favorite videos about the power of animations is this one — <a href="https://www.youtube.com/watch?v=Fy0aCDmgnxg">Juice it or lose it — a talk by Martin Jonasson &amp; Petri Purho</a>. If you don’t have time to check out the whole video at least watch the last 2 minutes. You’ll see just how much animations can change the feel of a design. Their demo game seems almost completely different despite the fact that all the game mechanics are exactly the same. While they are speaking of animations in terms of game design, the power that they can have is very clear. Plus they describe adding animations to something making it <em>juicey</em> which has got to be one of the most colorful ways to describe making a design more engaging!</p><p>Before we begin talking details, I think it is also important to note the difference between transitions and animations. Transitions are moving from some initial state to an end state. Animations are a little more complicated. While they can behave like transitions, moving from one state to the next, they can and often trigger multiple different states during the animation duration. Animations can chain multiple different states together causing all sorts of complex effects.</p><h3>How?</h3><h3>Basics</h3><p>Now that you’re hopefully psyched up about transitions and animations let’s discuss how to implement them in a Vue.js app to make it juicey! Luckily for us, Vue provides a transition wrapper component out of the box. It allows us to add enter and leave transtions for any element in one of four contexts:</p><ul><li>conditional rendering v-if</li><li>conditional display v-show</li><li>dynamic components is=&quot;component-name&quot;</li><li>component root nodes</li></ul><p>With this in mind, let’s dive in and see how to implement some transitions!</p><h3>Step-1 First Transition</h3><p>A good place to start is the createItem component. This component is made up of an &lt;input&gt; tag and some &lt;a&gt; tag action buttons. You can see that the actions are rendered conditionally using a v-if so that they are only visible when there is actually some text in the input box. This way we only allow the user to add an item when there is something to add. Let&#39;s add a transition to these buttons so that showing and hiding them is a little smoother and easier on the eyes.</p><p>First, we need to wrap our conditionally rendered html in a &lt;transition&gt; tag.</p><pre>... <br>&lt;transition&gt; <br>  &lt;div v-if=&quot;showActions&quot; class=&quot;buttons&quot;&gt; <br>    &lt;a v-on:click.stop.prevent=&quot;addItem()&quot; class=&quot;item-button add&quot;&gt;Add Item&lt;/a&gt; <br>    &lt;a v-on:click.stop.prevent=&quot;reset()&quot; class=&quot;item-button clear&quot;&gt;Clear&lt;/a&gt; <br>  &lt;/div&gt; <br>&lt;/transition&gt; <br>...</pre><p>createItem.js</p><p>Great! The transition tag wrapper will expose for us 6 CSS classes on the element that is conditionally rendered. In our case on &lt;div v-if=&quot;showActions&quot; class=&quot;buttons&quot;&gt;&lt;/div&gt;. These classes are:</p><ul><li>v-enter - starting state for enter</li><li>v-enter-active - active state for enter</li><li>v-enter-to - ending state for enter</li><li>v-leave - starting state for leave</li><li>v-leave-active - active state for leave</li><li>v-leave-to - ending state for leave</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9eWwcfVPYiRT3z8QAHhmg.png" /></figure><p>Here is a graphic to help illustrate these different states provided by the <a href="https://vuejs.org/v2/guide/transitions.html">vuejs transition documentation</a>. So let’s leverage these classes to create our transition and make the button fade in and out. Inside our animations.css file let&#39;s add the classes that we will need. We know that the transition occurs over the course of the active states for enter and leave so we know we will need v-enter-active and v-leave-active. We also will want to define the start and end states of the transition, so that we know what the element will look like when the transition has completed. So we will also use thev-enter and v-leave-to states.</p><pre>.v-enter-active, .v-leave-active {</pre><pre>} </pre><pre>.v-enter, .v-leave-to {</pre><pre>}</pre><p>animations.css</p><p>Now that we have all the classes we need, we can apply some css that will create the transition. Here we are trying to create a fade effect. A good css property to create this is opacity. And we also want to add a transition to this opacity, so we can use the transition css property!</p><pre>.v-enter-active, .v-leave-active {<br>  transition: opacity 1s;<br>} </pre><pre>.v-enter, .v-leave-to {<br>  opacity: 0;<br>}</pre><p>animations.css</p><p>That’s all there is to it! Now the buttons should fade in and out over one course of one second. You may want to tweak the transition duration to a time you see fit, I personally like 0.25s for my effects, but for learning purposes 1s is much more pronounced. This is awesome, but what if we wanted to add another transition on a different element? We wouldn&#39;t be able to do it cleanly as the name space of the transition states would collide. Lucky for us, the transition wrapper component can take a name attribute. This attribute will prefix our 6 css classes with that name. So let&#39;s make that change. Since it is a fade, let&#39;s name it fade!</p><pre>...<br>&lt;transition name=&quot;fade&quot;&gt;<br>  &lt;div v-if=&quot;showActions&quot; class=&quot;buttons&quot;&gt;<br>    &lt;a v-on:click.stop.prevent=&quot;addItem()&quot; class=&quot;item-button add&quot;&gt;Add Item&lt;/a&gt;<br>    &lt;a v-on:click.stop.prevent=&quot;reset()&quot; class=&quot;item-button clear&quot;&gt;Clear&lt;/a&gt;<br>  &lt;/div&gt;<br>&lt;/transition&gt;<br>...</pre><p>createItem.js</p><pre>.fade-enter-active, .fade-leave-active {<br>  transition: opacity 1s<br>}</pre><pre>.fade-enter, .fade-leave-to {<br>  opacity: 0<br>}</pre><p>animations.css</p><p>This allows us to scope and reuse our animations across our app! This is just an example of a simple transition, but the possibilities are endless.</p><h3>Step-2 List Transitions (adding &amp; removing items)</h3><p>Now that we know some of the basics about transitions, let’s tackle something a bit more challenging — adding transitions to the list items. Previously we used the transition component for an individual node being rendered conditionally. But what if you have many items being rendered using a v-for like in the case of the body of our todo list? Here the simple transition is not enough. For these scenarios, Vue provides the transition-group component wrapper. transition-group differs from transition in two ways.</p><ol><li>transition-group actually renders an element &lt;span&gt; by default that wrapps all of the elements in the list. You can change this wrapper element by defining the tag=&quot;&lt;el&gt;&quot; attribute on the transition-group component.</li><li>All of the list elements inside the transition-group must have a unique key attribute assigned to them. This helps for determining when an item has been added or removed from the list or has changed position.</li></ol><p>With that in mind let’s begin coding our transition. First let’s add the wrapper around our rendered list.</p><pre>...<br>&lt;transition-group name=&quot;list&quot;&gt;<br>  &lt;item v-for=&quot;(item, index) in items&quot; v-bind:key=&quot;item.id&quot; :item=&quot;item&quot; :index=&quot;index&quot; @togglechecked=&quot;passToggleChecked&quot; @change-priority=&quot;passChangePriority&quot;&gt;&lt;/item&gt;<br>&lt;/transition-group&gt;<br>...</pre><p>items.js</p><p>Let’s zero in on the important parts here. We have an &lt;item&gt; component that we are rendering as a list with v-for. We wrapped this component in a &lt;transition-group&gt; with the name list. And, we have bound a unique key on the item item.id. Now that we have taken care of everything in the markup, all we need to do is add the css hooks!</p><pre>.list-enter-active, .list-leave-active {<br>  transition: all 1s;<br>} </pre><pre>.list-enter, .list-leave-to {<br>  opacity: 0; <br>  transform: translateX(30px);<br>}</pre><p>animations.css</p><p>Here we are utilizing the different css states to slide in our newly added list items. However, one problem is that when we transition out the elements, the list snaps the elements into their new places. Wouldn’t it be much nicer if those elements gracefully slid to their new positions? We will tackle this next.</p><h3>Step-3 List Transitions (changing an items position)</h3><p>In the previous step we implemented a transition effect for adding and removing an item from a list. However, there is no transition effect for changing an items position in the list. We can see this problem when we remove an item as the other items snap to their new position, and also when we change the priority of an item.</p><p>This leads us to another concept of list-transitions - the v-move class. This class is added to a list item when its position is changing. This makes our job of adding a transition effect to any item that changes position really simple!</p><pre>.list-move {<br>  transition: transform 1s;<br>} </pre><pre>.list-enter-active, .list-leave-active {<br>  transition: all 1s; <br>  position: absolute; <br>  width: 100%;<br>} </pre><pre>.list-enter, .list-leave-to {<br>  opacity: 0; <br>  transform: translateX(30px);<br>}</pre><p>animations.css</p><p>Here we simply add the css move hook and give it a transition. We also can add an absolute position and width to our elements — leaving — hooks so that they are taken out of the flow of the list during the transition allowing the items that need to move the space to do so.</p><p>There we go! Now our list is much more responsive.</p><h3>Bonus (list animation)</h3><p>We spent all this time talking about transitions, let’s throw in an animation for fun!</p><p>Instead of a simple slide in, let’s make our list components bounce in and out of the list. Let’s change the name of our transition-group component so we don&#39;t tamper with our nice and neat list transition.</p><pre>...<br>&lt;transition-group name=&quot;list-bounce&quot;&gt;<br>  &lt;item v-for=&quot;(item, index) in items&quot; v-bind:key=&quot;item.id&quot; :item=&quot;item&quot; :index=&quot;index&quot; @togglechecked=&quot;passToggleChecked&quot; @change-priority=&quot;passChangePriority&quot;&gt;&lt;/item&gt;<br>&lt;/transition-group&gt;<br>...</pre><p>items.js</p><p>And let’s add a css animation on our active enter and leave css hooks.</p><pre>.list-bounce-enter-active, .list-bounce-leave-active {<br>  position: absolute; <br>  width: 100%;<br>} </pre><pre>.list-bounce-enter-active {<br>  animation: bounce-in .5s;<br>} </pre><pre>.list-bounce-leave-active {<br>  animation: bounce-in .5s reverse;<br>}</pre><pre>@keyframes bounce-in {<br>  0% {<br>    transform: scale(0);<br>  } <br>  50% {<br>    transform: scale(1.5);<br>  } <br>  100% {<br>    transform: scale(1);<br>  }<br>}</pre><p>animations.css</p><p>Here you’ll notice a couple things. We’ve defined a css animation called bounce-in. All it does is transform the scale of our element over some duration. You’ll notice that we’ve seperated out the animation on the enter-active and leave-active class so that we can play the animation fowards and backwards depending on the action. And finally our v-enter and v-leave-to hooks. They are not necessary because the animation takes care of this.</p><h3>Challenge</h3><p>There is one element left that we didn’t apply any transition or animation to! This is the &lt;div class=&quot;completed-action&quot;&gt; in app.js. Now that you know the basics of implementing Vue transitions and animations, try giving this button a fun new effect!</p><p>Also look out for the next post about transitions and animations using Vue. We will be looking at some more advanced concepts including creating reusable custom transitions, javascript hooks with transitions, and some other transitioning scenarios.</p><p><em>Originally published at </em><a href="https://gist.github.com/busster/c5f867be2c0e3caa818d80031c9e95dd"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3842d8b633ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/babystep/vuejs-transitions-3842d8b633ae">Vue.js Transitions</a> was originally published in <a href="https://medium.com/babystep">Babystep</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Vue (part 2 of 2)]]></title>
            <link>https://medium.com/babystep/introduction-to-vue-part-2-of-2-d57d296680ef?source=rss----9ae525615af6---4</link>
            <guid isPermaLink="false">https://medium.com/p/d57d296680ef</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[Marshall Shen]]></dc:creator>
            <pubDate>Sun, 20 Aug 2017 20:16:08 GMT</pubDate>
            <atom:updated>2017-08-22T03:18:53.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fyn8P2d7QOo0fZPHR2_UOw.png" /><figcaption>snapshot of demo, which is available at http://himarsh.org/tvinder</figcaption></figure><p>From <a href="https://medium.com/babystep/introduction-to-vue-part-1-of-2-c5d23e5a71aa">part 1</a>, you have learned the basics of Vue.js around components. Now let’s take it a step further and finish building the application!</p><p><strong>You can find the demo application </strong><a href="http://babystep.io/tvinder/"><strong>here</strong></a><strong>, and you can find the Github code </strong><a href="https://github.com/babystep-io/introduction-to-vuejs"><strong>here</strong></a><strong>.</strong></p><p>In part 2, you will learn:</p><ol><li>How to <strong>handle events</strong> and transmit data</li><li>How to use <strong>computed property</strong></li><li>(Advanced) How to use <strong>Vuex</strong> to manage states of an application</li></ol><h4>use events to transmit data</h4><p>Now that we know how to create a method that does some action, we want to implement our like, dislike, and skip methods. In this step let’s wire up those actions to influence our like count.</p><p>We will make like increment the count by 1, dislike decrement the count by 1 and skip will not do anything to the count. So our actions component will cause an action that changes the value of likes, and our header component will have to know when likes and dislikes change and render that value.</p><p>Looking at the structure of the app, we see that actions and header are siblings, and children of the tvinder-app component. We know that we can use props to pass data from parent to child, but how can we pass information from child to parent? <em>Every component has an event interface</em>. This allows the component to listen to an event, and trigger an event.</p><p>We saw the first of this interface in the previous step where we used v-on to listen for a click event. Here we will want to do both, trigger an event for one of our three actions (i.e. like, dislike, skip), and listen for that event on the parent component to register that something has happened.</p><p>Let’s add some necessary HTML markup so that we can use click events to fire off our methods. We will use some icons for our likes and dislikes buttons. Here is the markup that will render those icons and also listen for click events that will trigger our three methods.</p><p><strong>src/components/actions.js</strong></p><pre>... <br>&lt;div class=&quot;actions&quot;&gt; <br>  &lt;div class=&quot;controls&quot;&gt; <br>    &lt;div class=&quot;icon-button&quot; v-on:click=&quot;decrement()&quot;&gt; <br>      &lt;svg class=&quot;icon icon-cross&quot;&gt;&lt;use xlink:href=&quot;#icon-cross&quot;&gt;&lt;/use&gt;&lt;/svg&gt; <br>    &lt;/div&gt; <br>    &lt;a id=&quot;skip&quot; href=&quot;#&quot; v-on:click.prevent=&quot;skip&quot; class=&quot;icon-buttdon&quot;&gt;Skip&lt;/a&gt; <br>    &lt;div class=&quot;icon-button&quot; v-on:click=&quot;increment()&quot;&gt; <br>      &lt;svg class=&quot;icon icon-heart&quot;&gt;&lt;use xlink:href=&quot;#icon-heart&quot;&gt;&lt;/use&gt;&lt;/svg&gt; <br>    &lt;/div&gt; <br>  &lt;/div&gt; <br>&lt;/div&gt; <br>...</pre><p>Now that we have some markup to work with, let’s actually create our methods.</p><p><strong>src/components/actions.js</strong></p><pre>... <br>methods: { <br>  skip() { <br>    const self = this <br>    self.$emit(&#39;handleSkip&#39;) <br>  }, </pre><pre>  increment() { <br>    const self = this <br>    self.$emit(&#39;handleLikes&#39;, 1) <br>  }, </pre><pre>  decrement() { <br>    const self = this <br>    self.$emit(&#39;handleLikes&#39;, -1) <br>  } <br>} <br>...</pre><p>Here we are defining the three actions we want to perform. increment and decrement are equivalent to likeand dislike. So on click of the HTML element, each does the corresponding action.</p><p>The only thing that they do is $emit something. $emit() is part of the components event interface. Inside the parentheses, we must specify an eventName and an optional argument for any data we want to pass along. So increment() will emit an event with the name of handleLikes along with the value of 1. These events move upwards in the component tree. So the parent component of actions will be able to listen for an event with this name. 3. Now that we are emitting named events, we can listen for them on the parent component. We can capture these events that will trigger some action in the parent component.</p><p><strong>src/components/app.js</strong></p><pre>... <br>&lt;div&gt; <br>  &lt;app-header&gt;&lt;/app-header&gt; <br>  &lt;movies :image_url=&quot;image_url&quot;&gt;&lt;/movies&gt; <br><strong>  &lt;actions @handleLikes=&quot;handleLikes&quot; @handleSkip=&quot;handleSkip&quot;     &lt;/actions&gt; </strong><br>&lt;/div&gt; <br>...</pre><p>The way you listen for these events is with a directive on the HTML element. We declare this directive with an @ symbol and the event name we are listening for. So when we $emit(&#39;handleLikes&#39;) from actions.js @handleLikes will respond to that event. The second part to this directive is the method to call. This is the =&quot;handleLikes&quot; part.</p><p>All this mean is that the app fires off the handleLikes method on the component as the response to whatever event we have captured. Next we need to implement the methods that will fire when the app receives those events.</p><p><strong>app.js</strong></p><pre>... <br>methods: { <br><strong>  handleLikes(vote) { <br>    const self = this <br>    self.likes += vote <br>    self.incrementImage() <br>  }, </strong></pre><pre><strong>  handleDislikes(vote) {<br>    const self = this<br>    this.dislikes += vote<br>    self.incrementImage()<br>  }</strong></pre><pre>  handleSkip() { <br>    const self = this self.incrementImage() <br>  }, </pre><pre>  incrementImage() { <br>    // TODO <br>  } <br>} <br>...</pre><p>The last step is to add likes and disikes to our data function in app.js so that we can update that value, and pass it as a prop to our header component.</p><p><strong>src/components/app.js</strong></p><pre>... <br>&lt;app-header :likes=&quot;likes&quot; :dislikes=&quot;dislikes&quot;&gt;&lt;/app-header&gt; <br>...</pre><p><strong>src/components/header.js</strong></p><pre>... <br>props: { <br>  likes: { <br>    type: Number, <br>    required: true, <br>  },</pre><pre>  dislikes: { <br>    type: Number, <br>    required: true, <br>  },<br>} <br>...</pre><p>That’s it! Now we are updating our like count from our actions component.</p><h3>use computed properties to render movie data</h3><p>Here you will learn about computed properties! Now that we have most of the functionality built out, we will need to have some actual data to interact with. We have a json file with a list of movie objects with a movie name and a url that points to a poster of that movie. Up till now our templates have been very simple.</p><p>We have some data or some prop with a name and a value, and we simply bind that data in the template. But what if you have some data that is not a simple key value pairing? For instance, what if you had someone&#39;s name, but in the template you wanted to display their name backwards for some odd reason.</p><pre>... <br>&lt;div&gt; <br>  {{ name.split(&#39;&#39;).reverse().join(&#39;&#39;) }} <br>&lt;/div&gt; <br>...</pre><p>That looks kind of ugly, and you can imagine there could be much more complex pieces of logic for information you would want to render in the template. This is where computed properties come in handy. They can all this complex logic and allow us to simply use the name of that property in the template.</p><pre>... <br>&lt;div&gt; <br>  {{ <strong>reversedName</strong> }} <br>&lt;/div&gt; <br>... </pre><pre>computed: { <br><strong>  reversedName() { <br>    return this.name.split(&#39;&#39;).reverse().join(&#39;&#39;) <br>  } </strong><br>} <br>...</pre><p>This cleans up our templates and allows us to render our data more efficiently! So much the same as methods, computed is a custom attribute Vue implements. Inside the computed attribute, we declare functions for all of our computed properties. <strong>Any time a piece of data is updated, its computed property will also be updated</strong>.</p><p>With this in mind, let’s think about how we will interact with our data. We have a list of movie objects, and each has a key value pair of name and image url. We have a movies component that can render the name and image of one movie at a time. So, we should pass a movie object as a prop to our movies component.</p><p>But how will we select which movie to display from the list? One way would be to just randomly select a movie from the movies list and pass that in as a prop. But what if order matters or we don&#39;t want to potentially see the same movie twice? We can keep track of an index in the list to select a movie from, and pass the movie at that index to our movies component.</p><p>First let’s capture our movie-data and set up the initial index of that list we want to render.</p><p><strong>src/components/app.js</strong></p><pre>... <br>data() { <br>  return { <br>    likes: 0, <br>    dislikes: 0,<br>    <strong>imageIndex: 0, <br>    movieData: window.movieDataJson.posters </strong><br>  } <br>} <br>...</pre><p>We have already set movieData on the window so that we can easily use this JSON. Now that we have some data to work with, let’s pass that movie object to our movies component.</p><p><strong>src/components/app.js</strong></p><pre>... <br>&lt;div&gt; <br>  &lt;app-header :likes=&quot;likes&quot;&gt;&lt;/app-header&gt; <br><strong>  &lt;movies :movie=&quot;movie&quot;&gt;&lt;/movies&gt; <br></strong>  &lt;actions @handleLikes=&quot;handleLikes&quot; @handleSkip=&quot;handleSkip&quot;&gt;&lt;/actions&gt; <br>&lt;/div&gt; </pre><pre>... </pre><pre>computed: { <br><strong>  movie() { <br>   const self = this <br>   return self.movieData[self.imageIndex] <br>  } </strong><br>}, <br>...</pre><p>Here we are using a computed property to select which movie we will send as a prop to our movies component. We could also accomplish this directly in the template with something like &lt;movies :movie=&quot;movieData[imageIndex]&quot;&gt;&lt;/movies&gt;, but using a computed property is a cleaner approach.</p><p>Now that we are passing the movie object, we need to update our movies component to use this object. This means more computed properties! Instead of taking the image url directly from a prop, we are now getting it from our movie object.</p><p><strong>src/components/movies.js</strong></p><pre>... <br>const html = `<br>&lt;div class=&quot;movies&quot;&gt; <br>  &lt;div class=&quot;movie-poster-container&quot;&gt; <br>    &lt;img class=&quot;movie-poster&quot; v-bind:src=&quot;extractImageUrl&quot; v-bind:key=&quot;extractImageUrl&quot;&gt; <br>    &lt;div class=&quot;movie-name&quot;&gt;{{ extractImageName }}&lt;/div&gt; <br>  &lt;/div&gt; <br>&lt;/div&gt;<br>` <br>... <br>Vue.component(&quot;movies&quot;, { <br>  template: html, <br>  props: { <br>    movie: { <br>      type: Object, <br>      required: true, <br>    } <br>  }, <br>  ... <br>  computed: { <br><strong>    extractImageUrl() { <br>      const self = this return <br>      self.movie.url <br>    }, </strong></pre><pre><strong>    extractImageName() { <br>      const self = this <br>      return self.movie.name <br>    }  </strong><br>  }, </pre><pre>)<br>...</pre><p>Here we update our props to take in a movie object, and we define two computed properties to extract the information we want to bind to the template.</p><p>The last step is to implement our incrementImage() method on our app component so that when we like or dislike a movie, we cycle to the next movie.</p><p><strong>src/components/app.js</strong></p><pre>... <br>incrementImage() { <br>  const self = this </pre><pre>  self.imageIndex += 1 </pre><pre>  if(self.imageIndex &gt; (self.movieData.length-1)) { <br>    self.imageIndex = 0 } <br>  } <br>...</pre><h4>set up <strong>Vuex</strong></h4><p>In this step we will introduce Vuex state management system for our app. For a small app like this, Vuex might not be necessary, but it is a good starting point to learn the core concepts of Vuex.</p><p>So what is Vuex? It is a centralized store for every component in the app. It ensures that its state can only be mutated in a predictable way. Why would we want to use Vuex? There can be many answers to this question — but two good cases for implementing Vuex in your app are when:</p><ol><li>multiple components depend on the same piece of state</li><li>actions from different components have to mutate the same piece of state.</li></ol><p>At it’s basic level a Vuex Store looks like this:</p><pre>const Store = new Vuex.Store({ <br>  modules: { ... }, <br>  state: { ... }, <br>  getters: { ... }, <br>  mutations: { ... }, <br>  actions: { ... }, <br>})</pre><p>There are 5 core concepts to Vuex. They are <strong>state</strong>, <strong>actions</strong>, <strong>mutations</strong>, <strong>getters</strong>, and <strong>modules</strong>.</p><p>Let’s start by set up Vuex store, and we know that we want to keep track of likeand dislike , also specifically what movies are being liked or disliked. At the bottom we add <strong>window.store = Store</strong> so that the application has the store object.</p><p><strong>src/store/index.js</strong></p><pre>((() =&gt; {</pre><pre>  var Vuex = window.Vuex</pre><pre>  const Store = new Vuex.Store({<br> <strong>   state: {<br>      likes: 0,<br>      disLikes: 0,<br>      likedMovies: [],<br>      disLikedMovies: []<br>    },</strong><br>  )}</pre><pre>  window.store = Store</pre><pre>}))()</pre><p>Next we can define mutations that can change the states in the store. What is mutation? According to Vuex documentation:</p><blockquote>The only way to actually change state in a Vuex store is by committing a mutation. Vuex mutations are very similar to events: each mutation has a string type and a handler. The handler function is where we perform actual state modifications, and it will receive the state as the first argument.</blockquote><p>Let’s add mutation methods for each state:</p><p><strong>src/store/index.js</strong></p><pre>((() =&gt; {</pre><pre>  var Vuex = window.Vuex</pre><pre>  const Store = new Vuex.Store({<br>    state: {<br>      likes: 0,<br>      disLikes: 0,<br>      likedMovies: [],<br>      disLikedMovies: []<br>    },</pre><pre><strong>    mutations: {<br>      addToLikeCount(state, like) {<br>        state.likes += like<br>      },</strong></pre><pre><strong>      addToDislikeCount(state, disLike) {<br>        state.disLikes += disLike<br>      },</strong></pre><pre><strong>      addToDislikeArray(state, disLikedMovie) {<br>        state.disLikedMovies.push(disLikedMovie)<br>      },</strong></pre><pre><strong>      addToLikeArray(state, likedMovie) {<br>        state.likedMovies.push(likedMovie)<br>      }<br>    },</strong><br>  )}</pre><pre>  window.store = Store</pre><pre>}))()</pre><p>Now that we have <em>mutations</em> to change states within the store, we now build <em>actions</em> for other components to use. What is action? According to Vuex documentation:</p><blockquote>Actions are similar to mutations, the differences being that:</blockquote><blockquote>1. Instead of mutating the state, actions commit mutations.</blockquote><blockquote>2. Actions can contain arbitrary asynchronous operations.</blockquote><p>Even though this project doesn’t use all the features actions can provide, such as asynchronous operations, having actions being called outside the store and keep mutations private within store is a good practice.</p><p><strong>src/store/index.js</strong></p><pre>((() =&gt; {</pre><pre>var Vuex = window.Vuex</pre><pre>const Store = new Vuex.Store({<br>    state: {...},<br>    mutations: {...},</pre><pre><strong>    actions: {<br>      updateLikeCount(context, like) {<br>        context.commit(&quot;addToLikeCount&quot;, like)<br>      },</strong></pre><pre><strong>      updateDisLikeCount(context, dislike) {<br>        context.commit(&quot;addToDislikeCount&quot;, dislike)<br>      },</strong></pre><pre><strong>      updateDisLikedMovies(context, disLikedMovie) {<br>        context.commit(&quot;addToDislikeArray&quot;, disLikedMovie)<br>      },</strong></pre><pre><strong>      updateLikedMovies(context, likedMovie) {<br>        context.commit(&quot;addToLikeArray&quot;, likedMovie)<br>      }<br>    },</strong><br>  )}</pre><pre>  window.store = Store</pre><pre>}))()</pre><h4>wire up Vuex</h4><p>Now that we have Vuex setup, we can use it in our app! We have app.js as the source of truth for data rendered in the rest of views, so we can modify getters and setters within app.js to talk to our Vuex store!</p><p>Let’s start with getters, we will get data from our store using <strong><em>computed property</em></strong>.</p><p><strong>src/components/app.js</strong></p><pre>... <br>&lt;div&gt; <br>  &lt;app-header :likes=&quot;likes&quot;&gt;&lt;/app-header&gt; <br>  &lt;movies :movie=&quot;movie&quot;&gt;&lt;/movies&gt; <strong><br></strong>  &lt;actions @handleLikes=&quot;handleLikes&quot; @handleSkip=&quot;handleSkip&quot;&gt;&lt;/actions&gt; <br>&lt;/div&gt;</pre><pre>...</pre><pre>computed: { <br>  movie() { <br>    const self = this <br>    return self.movieData[self.imageIndex] <br>  },</pre><pre><strong>  likes() {<br>    const self = this<br>    return self.$store.state.likes<br>  },</strong></pre><pre><strong>  disLikes() {<br>    const self = this<br>    return self.$store.state.disLikes<br>  }</strong></pre><pre>}, <br>...</pre><p>next, we add setters to handle “like”, “dislike” or “skip” actions by using Vuex store. Whenever we want to trigger an action, we need to use <strong>store.dispatch</strong> method.</p><p><strong>src/components/app.js</strong></p><pre>...</pre><pre>computed: {},</pre><pre><strong>methods: {<br>  handleLikes(vote) {<br>    const self = this<br>    <br>    self.$store.dispatch(&quot;updateLikeCount&quot;, vote)<br>    self.$store.dispatch(&quot;updateLikedMovies&quot;, self.movie)<br>    self.incrementImage()<br>  },</strong></pre><pre><strong>  handleDisLikes(vote) {<br>    const self = this<br>        <br>    self.$store.dispatch(&quot;updateDisLikeCount&quot;, vote)<br>    self.$store.dispatch(&quot;updateDisLikedMovies&quot;, self.movie)<br>    self.incrementImage()<br>  },</strong></pre><pre><strong>  handleSkip() {<br>    const self = this<br>    <br>    self.incrementImage()<br>  },<br>} </strong><br>...</pre><h4>toggle modals using conditionals</h4><p>What if when we click on “votes” tab, we want to see a modal that shows details information of what we like or dislike? What if when we are done viewing that information, we want to close the modal and go back to where we were? This is where we can use v-show conditionals for toggling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dBQxXHqvHNz-j-AskrI7aw.png" /><figcaption>a detailed demo pops up when clicking on votes</figcaption></figure><p>First we need to create a component lists.js to capture the modal, and we get likedMovies and dislikedMovies from Vuex store. In addition, we use v-for to loop through the data collection.</p><p><strong>src/components/lists.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div class=&quot;modal&quot;&gt;<br>      &lt;div class=&quot;modal-content&quot;&gt;<br>        &lt;span class=&quot;close&quot;&gt;&amp;times;&lt;/span&gt;<br>        &lt;p&gt;Likes&lt;/p&gt;<br>          <strong>&lt;div v-for=&quot;movie in likedMovies&quot; id=&quot;likes&quot;&gt;<br>            {{ movie.name }}<br>          &lt;/div&gt;</strong><br>        &lt;p&gt;Dislikes&lt;/p&gt;<br>          <strong>&lt;div v-for=&quot;movie in disLikedMovies&quot; id=&quot;dislikes&quot;&gt;<br>            {{ movie.name }}<br>          &lt;/div&gt;</strong><br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `<br>  Vue.component(&quot;lists&quot;, {<br>    template: html,</pre><pre> <strong>   computed: {<br>      likedMovies() {<br>        const self = this<br>        return self.$store.state.likedMovies<br>      },</strong></pre><pre><strong>      disLikedMovies() {<br>        const self = this<br>        return self.$store.state.disLikedMovies<br>      }<br>    },</strong><br>   }<br> })</pre><pre>}))()</pre><p>Next we use v-show to toggle whether the modal should display or not. Essentially whenever v-show has a value true, Vue appends display:none CSS on the targeted element.</p><p>Who decides when to show the modal? We delegate that responsibility to the parent component v-show , and we pass a boolean prop showlists down to the child component. This pattern is called <strong>“data down”</strong>.</p><p>We first add the prop to the child component:</p><p><strong>src/components/lists.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div class=&quot;modal&quot; <strong>v-show=&quot;showLists&quot;</strong>&gt;<br>      &lt;div class=&quot;modal-content&quot;&gt;<br>        &lt;span class=&quot;close&quot;&gt;&amp;times;&lt;/span&gt;<br>        &lt;p&gt;Likes&lt;/p&gt;<br>          &lt;div v-for=&quot;movie in likedMovies&quot; id=&quot;likes&quot;&gt;<br>            {{ movie.name }}<br>          &lt;/div&gt;<br>        &lt;p&gt;Dislikes&lt;/p&gt;<br>          &lt;div v-for=&quot;movie in disLikedMovies&quot; id=&quot;dislikes&quot;&gt;<br>            {{ movie.name }}<br>          &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `<br>  Vue.component(&quot;lists&quot;, {<br>    template: html,</pre><pre><strong>    props: {<br>      showLists: {<br>        type: Boolean,<br>        required: true,<br>      }<br>    },</strong></pre><pre>   computed: {<br>     ...<br>   },</pre><pre>   methods: {<br>     closeModal() {<br>       const self = this</pre><pre>       self.$emit(&quot;closeModal&quot;)<br>     }<br>   }<br> })</pre><pre>}))()</pre><p>Now what happens if we click the close button on lists.js ? Rather than having the child component directly change data, it calls$emit function to broadcast an event to its parent component, then the parent component knows what to do upon receiving that event. This pattern is called <strong>“event up”</strong>.</p><p><strong>src/components/lists.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div class=&quot;modal&quot; v-show=&quot;showLists&quot;&gt;<br>      &lt;div class=&quot;modal-content&quot;&gt;<br>        &lt;span class=&quot;close&quot; <strong>v-on:click=&quot;closeModal()</strong>&quot;&gt;&amp;times;&lt;/span&gt;<br>        &lt;p&gt;Likes&lt;/p&gt;<br>          &lt;div v-for=&quot;movie in likedMovies&quot; id=&quot;likes&quot;&gt;<br>            {{ movie.name }}<br>          &lt;/div&gt;<br>        &lt;p&gt;Dislikes&lt;/p&gt;<br>          &lt;div v-for=&quot;movie in disLikedMovies&quot; id=&quot;dislikes&quot;&gt;<br>            {{ movie.name }}<br>          &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `<br>  Vue.component(&quot;lists&quot;, {<br>    template: html,</pre><pre>    props: {...},</pre><pre>    computed: {...},</pre><pre><strong>    methods: {<br>      closeModal() {<br>        const self = this</strong></pre><pre><strong>        self.$emit(&quot;closeModal&quot;)<br>      }<br>   }</strong><br> })</pre><pre>}))()</pre><p><strong>src/components/app.js</strong></p><pre>((() =&gt; {<br>  const html = `<br>    &lt;div&gt;<br>      ...<br>      <strong>&lt;lists :showLists=&quot;showLists&quot; </strong><a href="http://twitter.com/closeModal"><strong>@closeModal</strong></a><strong>=&quot;toggleShowLists&quot;&gt;&lt;/lists&gt;</strong><br>    &lt;/div&gt;<br>  `</pre><pre>Vue.component(&quot;tvinder-app&quot;, {<br>    template: html,<br>    data(){</pre><pre>      return {<br>        ...        <br>        <strong>showLists: false,</strong><br>      }<br>    },</pre><pre>    computed: {...},</pre><pre>    methods: {<br>      ...</pre><pre><strong>      toggleShowLists() {<br>        const self = this</strong></pre><pre><strong>        self.showLists = !self.showLists<br>      }</strong><br>    }<br>  })<br>}))()</pre><h3><strong>Conclusion</strong></h3><p>That’s it! You’ve now successfully built a web application using Vue, congratulations! To recap, in this tutorial we have covered:</p><ol><li>Core functionalities of Vue components</li><li>State management using Vuex</li><li>How to handle communication across different Vue components</li></ol><p><strong>You can find part 1 of this tutorial </strong><a href="https://medium.com/babystep/introduction-to-vue-part-1-of-2-c5d23e5a71aa"><strong>here</strong></a><strong>, the demo of the app is </strong><a href="http://himarsh.org/tvinder/"><strong>here</strong></a><strong>, and the Github code is </strong><a href="https://github.com/babystep-io/introduction-to-vuejs"><strong>here</strong></a><strong>.</strong></p><p>Let’s take baby steps to learn tech!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d57d296680ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/babystep/introduction-to-vue-part-2-of-2-d57d296680ef">Introduction to Vue (part 2 of 2)</a> was originally published in <a href="https://medium.com/babystep">Babystep</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>