Vue.js grid | Scoped Slots in Vue.js Components

Vue.js grid  | Scoped Slots in Vue.js Components

In this article, I will present a reusable grid component using scoped slots with dynamic names, but to make it easier to understand, I will start with some simpler examples.

The mechanism of slots in Vue.js makes it easier to create universal, reusable components. Slots are very powerful and at first may seem hard to use, especially the more advanced variants. In this article, I will present a reusable grid component using scoped slots with dynamic names, but to make it easier to understand, I will start with some simpler examples.

Default slot

If you’re using Vue.js, you probably already know the simplest kind of slot — the default slot:

<template>
  <button type="submit">
    <slot/>
  </button>
<template>

Such slot is simply a placeholder for the component’s content. This component can be used like this:

<SubmitButton>Submit</SubmitButton>

In this simple example, we could just use a text property instead of a slot. However, the content of a button can be more than just plain text — it might contain any HTML markup, for example an icon or image, or even a nested Vue.js component.

Also, using a slot more closely resembles the standard HTML <button> tag, so such code is easier to write and understand.

Scoped slot

One of most common use of a scoped slot is when a component is used to render an array of items, and we want to be able to customize the way each item is rendered.

The simplest example is an unordered list:

<template>
  <ul>
    <li v-for="( item, index ) in items" :key="index">
      <slot :item="item">{{ item }}</slot>
    </li>
  </ul>
</template>
<script>
export default {
  props: {
    items: { type: Array, required: true }
  }
}
</script>

You can see that the slot has an item property, which represents the currently rendered item. As you will later see, a scoped slot can contain as many properties as you need.

The slot also has fallback content, which simply displays each item as plain text. So in its simplest form, this component can be used to render an array of strings:

<SimpleList :items="[ 'Tom', 'Felix', 'Sylvester' ]"/>

However, the component can be customized to display an array of more complex objects. Consider the following example:

<template>
  <SimpleList :items="cats">
    <template v-slot="{ item: cat }">
      {{ cat.name }}, {{ cat.age }} years old
    </template>
  </SimpleList>
</template>
<script>
export default {
  data() {
    return {
      cats: [
        { name: 'Tom', age: 3 },
        { name: 'Felix', age: 5 },
        { name: 'Sylvester', age: 7 }
      ]
    };
  }
}
</script>

As you can see, the parent component can retrieve the value of the item property using the special v-slot directive. We can even rename the property to make the code more readable — in our example, we can access the current item using the cat variable. This works just like object destructuring, where you can assign object properties to variables and optionally rename them.

Note that using a <template> element isn’t necessary if you have just one default slot. So the above code could be written like this:

<template>
  <SimpleList :items="cats" v-slot="{ item: cat }">
    {{ cat.name }}, {{ cat.age }} years old
  </SimpleList>
</template>
Grid component — simple version

What if we want to display the above data as a table? We could use a similar approach and use a default scoped slot:

<template>
  <table>
    <thead>
      <tr>
        <th v-for="( column, prop ) in columns" :key="prop">
          {{ column }}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="( row, index ) in rows" :key="index">
        <td v-for="( _, prop ) in columns" :key="prop">
          <slot :row="row" :prop="prop">
            {{ row[ prop ] }}
          </slot>
        </td>
      </tr>
    </tbody>
  </table>
</template>
<script>
export default {
  props: {
    columns: { type: Object, required: true },
    rows: { type: Array, required: true }
  }
}
</script>

The columns property of the grid component is an object which maps column names to their header text. The rows property is an array of objects representing the rows of the table.

You can see that the body of the table contains two nested v-for loops. The outer loop iterates over the elements of the rows array, and the inner v-for loop iterates over the properties of the columns object.

The scoped slot now has two properties, row which represents the current row, and prop which represents the name of the current column. The default content simply extracts the value from the row and displays it as plain text.

In the simplest case, this component can be used like this:

<template>
  <SimpleGrid :columns="columns" :rows="cats"/>
</template>
<script>
export default {
  data() {
    return {
      cats: [
        { name: 'Tom', age: 3 },
        { name: 'Felix', age: 5 },
        { name: 'Sylvester', age: 7 }
      ]
    };
  },
  computed: {
    columns() {
      return { name: 'Name', age: 'Age' };
    }
  }
}
</script>

Because the grid component uses a slot, we can customize the way the individual cells are rendered. In a typical grid component, different columns are rendered in different ways, depending on their type. To demonstrate this, let’s add a third column which displays images instead of text:

<template>
  <SimpleGrid :rows="cats">
    <template v-slot="{ row: cat, prop }">
      <img v-if="prop == 'image'" :src="cat.image">
    </template>
  </SimpleGrid>
</template>
<script>
export default {
  data() {
    return {
      cats: [
        { name: 'Tom', age: 3, image: 'tom.jpg' },
        { name: 'Felix', age: 5, image: 'felix.jpg' },
        { name: 'Sylvester', age: 7, image: 'sylvester.jpg' }
      ]
    };
  },
  computed: {
    columns() {
      return { name: 'Name', age: 'Age', image: 'Image' };
    }
  }
}
</script>

Note that our slot template contains conditional code that checks the name of the current column, represented by the prop variable. The <img> tag is only rendered for the image column, otherwise the template will not render anything and the fallback content will be used.

This works fine in this simple example, but if there are many different columns, this code can become hard to read and ineficient. For example, if we want to also customize the age column, we would have to write the following code:

<template>
  <SimpleGrid :rows="cats">
    <template v-slot="{ row: cat, prop }">
      <template v-if="prop == 'age'">
        {{ cat.age }} years old
      </template>
      <img v-else-if="prop == 'image'" :src="cat.image">
    </template>
  </SimpleGrid>
</template>

As the grid becomes more complex, we have to add more v-else-if directives, which is not a very elegant solution.

Named slots

So far we’ve been using a default slot, but aVue.js component can contain multiple slots with different names. For example, a page layout component could contain a default slot for the page content and named slots for the header and footer:

<template>
  <div class="header">
    <slot name="header"/>
  </div>
  <slot/>
  <div class="footer">
    <slot name="footer"/>
  </div>
</template>

However, the names of slots don’t have to be hard-coded. We can use dynamic slot names using the v-bind:name syntax or the abbreviated :name syntax. This can be very useful for creating a better version of our grid component.

Grid component using named slots

Let’s modify the grid in the following way:

<template>
  <table>
    <thead>
      <tr>
        <th v-for="( column, prop ) in columns" :key="prop">
          {{ column }}
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="( row, index ) in rows" :key="index">
        <td v-for="( _, prop ) in columns" :key="prop">
          <slot :name="'cell-' + prop" :row="row">
            {{ row[ prop ] }}
          </slot>
        </td>
      </tr>
    </tbody>
  </table>
</template>
<script>
export default {
  props: {
    columns: { type: Object, required: true },
    rows: { type: Array, required: true }
  }
}
</script>

The only change is the highlighted line. As you can see, the slot is no longer a default slot; it’s a named slot with a dynamic name which depends on the name of the columns. So in our example, the component has three slots, named cell-name, cell-age and cell-image.

The parent component can use these named slots in the following way:

<template>
  <SimpleGrid :columns="columns" :rows="cats">
    <template v-slot:cell-age="{ row: cat }">
      {{ cat.age }} years old
    </template>
    <template v-slot:cell-image="{ row: cat }">
      <img :src="cat.image">
    </template>
  </SimpleGrid>
</template>
<script>
export default {
  // same as before
}
</script>

Two custom templates are defined for the cell-age and cell-image slots, and the first column will display the fallback content.

The code becomes more elegant and easier to understand, because you can immediately see which template is associated with each column and no conditional directives are necessary.

This technique can be used to add another small improvement to our grid component — we can wrap column headers in a dynamically named slot:

<thead>
  <tr>
    <th v-for="( column, prop ) in columns" :key="prop">
      <slot :name="'header-' + prop">
        {{ column }}
      </slot>
    </th>
  </tr>
</thead>

Now, there are three additional named slots, header-name, header-age and header-image, which can be used to replace the content of the individual column headers, for example to add filters or sort links.

Final notes

Note that all these code examples use the new syntax of slots which was introduced in version 2.6 of Vue.js. In older versions such elegant solution wouldn’t be possible, so this is a big and often underestimated improvement.

You can use the shorthand syntax and replace the v-slot prefix with the # symbol, though I personally prefer to use the more verbose version. Perhaps it’s just a matter of getting used to the new syntax.

Slots are one of the most complex features of Vue.js and learning to fully take advantage of them may take some time, but it’s definitely worth the effort. You can find many other useful examples in the official Vue.js documentation and also in the RFC document in which the new syntax was proposed.

JavaScript Tutorial: if-else Statement in JavaScript

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

Decision Making in programming is similar to decision making in real life. In programming also we face some situations where we want a certain block of code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.

JavaScript’s conditional statements:

  • if
  • if-else
  • nested-if
  • if-else-if

These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

  • if: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
    Syntax:
if(condition) 
{
   // Statements to execute if
   // condition is true
}

Here, condition after evaluation will be either true or false. if statement accepts boolean values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if statement will consider the immediate one statement to be inside its block. For example,

if(condition)
   statement1;
   statement2;

// Here if the condition is true, if block 
// will consider only statement1 to be inside 
// its block.

Flow chart:

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If statement 

var i = 10; 

if (i > 15) 
document.write("10 is less than 15"); 

// This statement will be executed 
// as if considers one statement by default 
document.write("I am Not in if"); 

< /script> 

Output:

I am Not in if
  • if-else: The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.
    Syntax:
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}


Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate If-else statement 

var i = 10; 

if (i < 15) 
document.write("10 is less than 15"); 
else
document.write("I am Not in if"); 

< /script> 

Output:

i is smaller than 15
  • nested-if A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, JavaScript allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.
    Syntax:
if (condition1) 
{
   // Executes when condition1 is true
   if (condition2) 
   {
      // Executes when condition2 is true
   }
}

Example:

<script type = "text/javaScript"> 

// JavaScript program to illustrate nested-if statement 

var i = 10; 

if (i == 10) { 

// First if statement 
if (i < 15) 
	document.write("i is smaller than 15"); 

// Nested - if statement 
// Will only be executed if statement above 
// it is true 
if (i < 12) 
	document.write("i is smaller than 12 too"); 
else
	document.write("i is greater than 15"); 
} 
< /script> 

Output:

i is smaller than 15
i is smaller than 12 too
  • if-else-if ladder Here, a user can decide among multiple options.The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
if (condition)
    statement;
else if (condition)
    statement;
.
.
else
    statement;


Example:

<script type = "text/javaScript"> 
// JavaScript program to illustrate nested-if statement 

var i = 20; 

if (i == 10) 
document.wrte("i is 10"); 
else if (i == 15) 
document.wrte("i is 15"); 
else if (i == 20) 
document.wrte("i is 20"); 
else
document.wrte("i is not present"); 
< /script> 

Output:

i is 20

How to Retrieve full Profile of LinkedIn User using Javascript

How to Retrieve full Profile of LinkedIn User using Javascript

I am trying to retrieve the full profile (especially job history and educational qualifications) of a linkedin user via the Javascript (Fetch LinkedIn Data Using JavaScript)

Here we are fetching LinkedIn data like Username, Email and other fields using JavaScript SDK.

Here we have 2 workarounds.

  1. Configuration of linkedIn developer api
  2. Javascript Code to fetch records

Configuration of linkedIn developer api

In order to fetch records, first we need to create developer api in linkedin which will act as token/identity while fetching data from other linkedin accounts.

So to create api, navigate to https://linkedin.com/developer/apps and click on 'Create Application'.

After navigating, fill in details like name, description and other required fields and then submit.

As we submit, it will create Client ID and Client Secret shown below, which we will be using in our code while communicating to fetch records from other LinkedIn account.

Note: We need to provide localhost Url here under Oauth 2.0. I am using my localhost, but you can probably use other production URLs under Oauth 2.0 where your app is configured. It will make your api  consider the Url as trusted which fetching records.

Javascript Code to fetch records

For getting user details like first name, last name,User image can be written as,

<script type="text/javascript" src="https://platform.linkedin.com/in.js">  
    api_key: XXXXXXX //Client ID  
    onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load  
    authorize: true  
</script>  
<script type="text/javascript">  
    function OnLinkedInFrameworkLoad() {  
        IN.Event.on(IN, "auth", OnLinkedInAuth);  
    }  
  
    function OnLinkedInAuth() {  
        IN.API.Profile("me").result(ShowProfileData);  
    }  
  
    function ShowProfileData(profiles) {  
        var member = profiles.values[0];  
        var id = member.id;  
        var firstName = member.firstName;  
        var lastName = member.lastName;  
        var photo = member.pictureUrl;  
        var headline = member.headline;  
        //use information captured above  
        var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: " + lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline + "<p/>"  
        document.getElementById('profiles').innerHTML = stringToBind;  
    }  
</script>    

Kindly note we need to include 'https://platform.linkedin.com/in.js' as src under script type as it will act on this Javascript SDK provided by Linkedin.

In the same way we can also fetch records of any organization with the companyid as keyword.

<head>  
    <script type="text/javascript" src="https://platform.linkedin.com/in.js">  
        api_key: XXXXXXX ////Client ID  
        onLoad: onLinkedInLoad  
        authorize: true  
    </script>  
</head>  
  
<body>  
    <div id="displayUpdates"></div>  
    <script type="text/javascript">  
        function onLinkedInLoad() {  
            IN.Event.on(IN, "auth", onLinkedInAuth);  
            console.log("On auth");  
        }  
  
        function onLinkedInAuth() {  
            var cpnyID = XXXXX; //the Company ID for which we want updates  
            IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=10&format=json").result(displayCompanyUpdates);  
            console.log("After auth");  
        }  
  
        function displayCompanyUpdates(result) {  
            var div = document.getElementById("displayUpdates");  
            var el = "<ul>";  
            var resValues = result.values;  
            for (var i in resValues) {  
                var share = resValues[i].updateContent.companyStatusUpdate.share;  
                var isContent = share.content;  
                var isTitled = isContent,  
                    isLinked = isContent,  
                    isDescription = isContent,  
                    isThumbnail = isContent,  
                    isComment = isContent;  
                if (isTitled) {  
                    var title = isContent.title;  
                } else {  
                    var title = "News headline";  
                }  
                var comment = share.comment;  
                if (isLinked) {  
                    var link = isContent.shortenedUrl;  
                } else {  
                    var link = "#";  
                }  
                if (isDescription) {  
                    var description = isContent.description;  
                } else {  
                    var description = "No description";  
                }  
                /* 
                if (isThumbnailz) { 
                var thumbnailUrl = isContent.thumbnailUrl; 
                } else { 
                var thumbnailUrl = "http://placehold.it/60x60"; 
                } 
                */  
                if (share) {  
                    var content = "<a target='_blank' href=" + link + ">" + comment + "</a><br>";  
                    //el += "<li><img src='" + thumbnailUrl + "' alt=''>" + content + "</li>";  
                    el += "<li><div>" + content + "</div></li>";  
                }  
                console.log(share);  
            }  
            el += "</ul>";  
            document.getElementById("displayUpdates").innerHTML = el;  
        }  
    </script>  
</body>  

We can get multiple metadata while fetching records for any any organization. We can get company updates as shown below.

Conclusion

We can also fetch any company specific data like company job updates/post, total likes, comments, and number of views along with a lot of metadata we can fetch which I have shown below.

Thank you for reading !

Making a Game in VueJS using Vuex | VueJS Tutorial

Making a Game in VueJS using Vuex | VueJS Tutorial

Today we create a Game in VueJS using Vuex to manage our state. This is an open source community driven game and I would love for you to get involved. We explore the game loop, upgrades, levelling and much more

Today we create a Game in VueJS using Vuex to manage our state. This is an open source community driven game and I would love for you to get involved. We explore the game loop, upgrades, levelling and much more. We looking into VueJS lifecycle methods as well as Vuex mutations, getters and state.

A Javascript Project

Day 15 #31Days31Videos