Showing posts with label vue 2. Show all posts
Showing posts with label vue 2. Show all posts

Sunday, July 24, 2022

How to watch the change in arrays and objects in VueJs

In this tutorial, we will learn how to watch the nested data like arrays and objects in Vue.js

Watching Props Arrays:

export default {
  name: "ComponentName",
  props: {
    users: {
      type: Array,
      required: true,
    },
  },
  watch: {
    users: {
      deep: true,
      handler(newValue, oldValue) {
        console.log("Manipulate new and old value here")
      }
    }
  },
}

Here we are using the users array and watching it inside the watch block. deep: true will let Vue to watch inside the array and the handler will give the old and new values.

Watching Objects:

export default {
  name: "ComponentName",
  data() {
    return {
      entity: {
        properties: [],
        propertyOne:'',
        propertyTwo:''
      }
    }
  },
  watch: {
    entity: {
      deep: true,
      handler(newValue, oldValue) {
        console.log("Manipulate new and old value here")
      }
    }
  },
}

Here, we are creating the entity object and watching it in the watch block. Here it will deep watch the whole entity object.

Watching properties of Objects:

If we don't want to watch for every change on the object, we can watch every single entity as well

export default {
  name: "ComponentName",
  data() {
    return {
      entity: {
        properties: [],
        propertyOne:'',
        propertyTwo:''
      }
    }
  },
  watch: {
    'entity.properties': {
      handler(newValue, oldValue) {
        console.log("Manipulate new and old value here")
      },
      deep: true
    },
    'entity.propertyOne': {
      handler(newValue, oldValue) {
        console.log("Manipulate new and old value here")
      },
    },
  },
}

Watching properties of Objects using computed:

export default {
  name: "ComponentName",
  data() {
    return {
      entity: {
        properties: [],
        propertyOne:'',
        propertyTwo:''
      }
    }
  },
  computed: {
    entityPropertyOne() {
      return this.entity.propertyOne;
    }
  },
  watch: {
    entityPropertyOne: {
      handler(newValue, oldValue) {
        console.log("Manipulate new and old value here")
      },
    },
  },
}
Share:

Saturday, July 9, 2022

How to call parent window function from child window in javascript

In this tutorial, we will learn how to call the parent window function from the child window in javascript.

In some cases, we need to open the child browser window as a modal or dialog. For example, if need to handle and load the redirect URL in a single-page application.

While using third-party services providers for e.g PayPal we are supposed to get the redirect URL to load the payment page for security reasons. In this case, we will load that redirect URL in the child window as a modal and the user will proceed with the payment securely. Once the payment is done we need to notify the parent window or our single-page application that the payment got succeeded or pass some token. In this case, we need to call the parent window function from the child window.

Let's look into the example, where we are passing token from the child window to the parent function.

Here, while opening the child window we will register the function in the document interface that represents any web page loaded in the browser and serves as an entry point into the web page's content

document.responseToken = function (token){
          // manuplate the token
        }

Now let's add the calling function from the child window.

window.opener.document.responseToken(token);
        window.close();

Here, we are using window.opener The Window interface's opener property returns a reference to the window that opened the window i.e parent window. So we can get the responseToken function that we registered previously. This will pass the token to the reference or parent window. After that window.close() will close the child dialog window.

Share:

Saturday, July 2, 2022

Vue.js How to get query parameter from URL

In this tutorial, we are going to learn how we can get the query parameter from URL.

let's look into the sample example.

http://360learntocode.com?username=test

Using Vue Router:

Here, we want to get the username query parameter. In Vue.js there is an elegant way to get query parameters. If we are using the router then we can get the parameter inside the vue.js component as below.

let username =  this.$route.query.username

Which gives the username value. Another way to get parameters with the router is

let username = this.$route.params.username

Using Javascript URLSearchParams :

We can use URLSearchParams() method which helps to work with the query string of the URL. We can use this inside our vue.js component methods as below.

 methods: {
    getUsername() {
      const queryString = window.location.search;
      if (queryString) {
        const urlParams = new URLSearchParams(queryString);
      	if (urlParams.has('username')) {
          return urlParams.get('username');
        }
      }
      return "";
    }
  }

Or

 methods: {
    getUsername() {
      const queryString = window.location.href;
      if (queryString) {
      	let urlString = queryString.split('?')[1]
        const urlParams = new URLSearchParams(urlString);
      	if (urlParams.has('username')) {
          return urlParams.get('username');
        }
      }
      return "";
    }
  }
Share:

Friday, January 14, 2022

How to remove hash mode(#) from URL in VueJs application

This is a quick tutorial on how we can get rid of hash mode(#) from the URL in the Vue.js application

While using Vue router, the default mode is a hash mode. So when the user tries to load the page like http://localhost:8080/invalid/url then it will redirect to the base URL with hash.

We can simply remove hash mode by adding history mode while initializing the Vue router

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

This initialization can be found under folder >> src >> router >> index.js if we initialized the application with router setup using Vue CLI. Or in main.js file.

Once we remove the hash mode the user with an invalid URL might get a 404 not found error. For this, we need to manage the configuration in the server where we deploy the application.

For this, we need to configure in such a way that for the invalid users, we will redirect the user to index.html page which will open the base URL of the application.

In Nginx

location / {
  try_files $uri $uri/ /index.html;
}

In Apache

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
</IfModule>

In Firebase inside firebase.json add the following JSON config

{
  "hosting": {
    "public": "dist",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

For more server configuration please visit the vue-router page.

Share:

Adding global CSS in VueJs application

This is a quick tutorial on how we can add the global CSS in the Vue.js application.

In each Vue.js component, we can add the component-based CSS which means the CSS will only be applicable for that component.

This can be done by using the scoped keyword in style tag inside the component as below:

<template>
   <div>
    </div>
</template>

<script>
  
</script>

<style scoped>
    /*add your css here*/
    
</style>

If we have the common CSS, we need to use a global CSS file to add it and use the class name inside the HTML element inside components.

For this, let's create a css folder under src >> assets and add a main.css file. This file will contain all the global CSS.

Now, we need to import the created CSS file; which can be done under the main.js file. Import the file as below

import './assets/css/main.css';

If we want to add multiple global CSS files we can simply add the file and import it in main.js as described.

Share:

Change the HTML title tag and favicon icon on newly created VueJs application

This is a quick tutorial on how we can change the HTML document title and favicon in the Vue.js application

If we are creating the VueJs application with Vue CLI then it will automatically import the project name as HTML title and default VueJs favicon icon.

To change this, go to the project directory, we can see the public folder there we can find the index.html file if we open the file we can see the title tag as below:


<title><%= htmlWebpackPlugin.options.title %></title>

Simply remove the dynamically imported content inside the tag and add the desired title to it

<title>360learntocode</title>

Now let's change the default favicon. For this, go to the same public directory where we can see the favicaon.icon.

Simply replace your favicon icon here with the same name or if we want to use it with a different name then change the name inside index.html file

<link rel="icon" href="<%= BASE_URL %>360learntocode.ico">
Share:

Thursday, January 13, 2022

How to use share functionality using web share API in VueJs application

In this tutorial, we are going to implement the web share functionality using Web Share API.

Web Share API is not supported for all browsers. We can see the supported browser for this API from caniuse.


Please follow the tutorial for sharing on social media platforms.

The Web Share API provides a mechanism for sharing links, text, files, and other content utilizing the sharing mechanisms of the underlying operating system. Note that this API only can be used over the secure connection HTTPS.

Sharing Links and Text Description

Let's create a sample vue component called Share.vue and add the following HTML inside the template which contains a simple button to allow users for sharing.

<div class="share" v-if="isSupported">
    <button class="button" @click="webShare">Share</button>
</div>
.button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

Here, if the browser supports the API, we are rendering the share button to allow the user to share. If not then we are hiding the button. Now, let's add the data and method used

created() {
    this.isSupport();
  },
  data () {
    return {
      isSupported : false,
      url : "https://caniuse.com/web-share",
      title:"Web API Share",
      description: "Web API Sharing"
    }
  },
  methods: {
    isSupport() {
      if (navigator.share) {
        this.isSupported = true;
      }
    },
    webShare() {
      let self = this;
      navigator.share({
        title: self.title,
        text: self.description,
        url: self.url
      })
    }
  }
}

webShare function allows the user to share link and title and description on different applications of OS.

Sharing Files

webShare() {
      let self = this;
      fetch("file_url").then(function (response) {
        return response.blob()
      }).then(function (blob) {
        let file = new File([blob], "picture.jpg", {type: 'image/jpeg'});
        let filesArray = [file];
        if (navigator.canShare && navigator.canShare({files: filesArray})) {
          navigator.share({
            title: self.title,
            text: self.description,
            files: filesArray,
            url: self.url
          });
        }
      });
    }

If we want to share the file, first load the file and test whether the file can be sharable or not, if it is sharable then it will be shared over the available supported application of OS.

The overall implementation looks as below:

<template>
    <div class="share" v-if="isSupported">
        <button class="button" @click="webShare">Share</button>
    </div>
</template>

<script>
    export default {
        name: "Share",
        created() {
            this.isSupport();
        },
        data () {
            return {
                isSupported : false,
                url : "https://www.360learntocode.com/2022/01/how-to-implement-social-media-share.html",
                title:"Web API Share",
                description: "Web API Sharing"
            }
        },
        methods: {
            isSupport() {
                if (navigator.share) {
                    this.isSupported = true;
                }
            },
            webShare() {
                let self = this;
                navigator.share({
                    title: self.title,
                    text: self.description,
                    url: self.url
                })
            }
        }
    }
</script>

<style scoped>
    .button {
        background-color: #4CAF50;
        border: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
    }
</style>
Share:

Sunday, January 9, 2022

Create UTC count down timer in VueJs

In this tutorial, we are going to learn how to create a UTC countdown timer in VueJs. We are UTC time to manipulate the countdown timer so that every user from different locations can see the same countdown.

Let's create a component called CountDownTimer.vue

Now, let's add some HTML and CSS for the countdown timer in the template.

<div v-if="displayCountDown">
    <h2 class="text-animation" v-if="isLive">Sale is now LIVE</h2>
    <div v-else>
        <h2 class="text-animation">Sale starts in:</h2>
        <section>
            <section class="timer">
                <div>
                    <section>
                        <p>{{ days }}</p>
                        <p>
                            <small>Days</small>
                        </p>
                    </section>
                    <span>:</span>
                    <section>
                        <p>{{ hours }}</p>
                        <p>
                            <small>Hours</small>
                        </p>
                    </section>
                    <span>:</span>
                    <section>
                        <p>{{ minutes }}</p>
                        <p>
                            <small>Minutes</small>
                        </p>
                    </section>
                    <span>:</span>
                    <section>
                        <p>{{ seconds }}</p>
                        <p>
                            <small>Seconds</small>
                        </p>
                    </section>
                </div>
            </section>
        </section>
    </div>
</div>
<style scoped>
    .timer {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .timer div:first-child {
        border: 1px solid white;
        border-radius: 3px;
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        text-align: center;
        margin-bottom: 1em;
        padding: 1em 1em 0 1em;
    }

    section p:first-child,
    .timer div:last-child span {
        display: contents;
    }

    @media screen and (max-width: 480px) {
        .timer div:last-child {
            margin-left: 2em;
            margin-right: 2em;
        }
    }

    .text-animation {
        animation: color-change 5s infinite;
        font-weight: 400;
    }

    @keyframes color-change {
        0% {
            color: #00FFA3;
        }
        25% {
            color: yellow;
        }
        50% {
            color: #DC1FFF;
        }
        75% {
            color: #F1A945;
        }
        100% {
            color: #00FFA3;
        }
    }
</style>

Add the data used inside the template

data() {
    return {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      isLive: false,
      displayCountDown: false
    }
  },

Create a function called startTimer where we are going to add the timmer logic.

methods: {
    startTimer() {
      const countdownDate = new Date("January 11, 2022 7:59:00").getTime(); // always use UTC time
      let self = this;
      let interval = setInterval(() => {
        const now = new Date();
        let nowUTC = new Date(
            now.getUTCFullYear(),
            now.getUTCMonth(),
            now.getUTCDate(),
            now.getUTCHours(),
            now.getUTCMinutes(),
            now.getUTCSeconds()
        ).getTime();
        const distance = countdownDate - nowUTC;
        const days = Math.floor(distance / (1000 * 60 * 60 * 24));
        const hours = Math.floor(
            (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
        );
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);
        if (distance <= 0) {
          self.isLive = true;
          clearInterval(interval);
        } else {
          self.days = days;
          self.hours = hours;
          self.minutes = minutes;
          self.seconds = seconds;
        }
        self.displayCountDown = true;
      }, 1000);
    }
  }

Here, first, create the UTC time when the action will happen i.e for e.g the time when the sale starts. Make sure that the time needs to be UTC time.

const countdownDate = new Date("January 11, 2022 7:59:00").getTime(); // always use UTC time

After that, we are using setInterval() method which repeatedly calls a function or executes a code snippet inside it, with a fixed time delay between each call.

Note there we are using 1000 ms time so that the countdown will refresh in every second.

Let's look into the below code

 const now = new Date();
        let nowUTC = new Date(
            now.getUTCFullYear(),
            now.getUTCMonth(),
            now.getUTCDate(),
            now.getUTCHours(),
            now.getUTCMinutes(),
            now.getUTCSeconds()
        ).getTime();

We are getting the current data which gives the current location browser data. We have to convert this to UTC current date. So the user from a different location can see the same countdown

After that, we are calculating distance which will show the countdown is expired or not and days, hours, minutes, and seconds.

If the countdown is expired then we are clearing the setInterval and hiding the countdown and showing some desired text

Start the countdown timer. For this, simply call the startTimer function from created hook.

created() {
    this.startTimer();
  },

The demo output for this example looks like below:


The overall code implementation looks as below:

<template>
    <div v-if="displayCountDown">
        <h2 class="text-animation" v-if="isLive">Sale is now LIVE</h2>
        <div v-else>
            <h2 class="text-animation">Sale starts in:</h2>
            <section>
                <section class="timer">
                    <div>
                        <section>
                            <p>{{ days }}</p>
                            <p>
                                <small>Days</small>
                            </p>
                        </section>
                        <span>:</span>
                        <section>
                            <p>{{ hours }}</p>
                            <p>
                                <small>Hours</small>
                            </p>
                        </section>
                        <span>:</span>
                        <section>
                            <p>{{ minutes }}</p>
                            <p>
                                <small>Minutes</small>
                            </p>
                        </section>
                        <span>:</span>
                        <section>
                            <p>{{ seconds }}</p>
                            <p>
                                <small>Seconds</small>
                            </p>
                        </section>
                    </div>
                </section>
            </section>
        </div>
    </div>
</template>

<script>
    export default {
        name: "CountDownTimer",
        created() {
            this.startTimer();
        },
        data() {
            return {
                days: 0,
                hours: 0,
                minutes: 0,
                seconds: 0,
                isLive: false,
                displayCountDown: false
            }
        },
        methods: {
            startTimer() {
                const countdownDate = new Date("January 11, 2022 7:59:00").getTime();
                let self = this;
                let interval = setInterval(() => {
                    const now = new Date();
                    let nowUTC = new Date(
                        now.getUTCFullYear(),
                        now.getUTCMonth(),
                        now.getUTCDate(),
                        now.getUTCHours(),
                        now.getUTCMinutes(),
                        now.getUTCSeconds()
                    ).getTime();
                    const distance = countdownDate - nowUTC;
                    const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                    const hours = Math.floor(
                        (distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
                    );
                    const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                    const seconds = Math.floor((distance % (1000 * 60)) / 1000);
                    if (distance <= 0) {
                        self.isLive = true;
                        clearInterval(interval);
                    } else {
                        self.days = days;
                        self.hours = hours;
                        self.minutes = minutes;
                        self.seconds = seconds;
                    }
                    self.displayCountDown = true;
                }, 1000);
            }
        }
    }
</script>

<style scoped>
    .timer {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .timer div:first-child {
        border: 1px solid white;
        border-radius: 3px;
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        text-align: center;
        margin-bottom: 1em;
        padding: 1em 1em 0 1em;
    }

    section p:first-child,
    .timer div:last-child span {
        display: contents;
    }

    @media screen and (max-width: 480px) {
        .timer div:last-child {
            margin-left: 2em;
            margin-right: 2em;
        }
    }

    .text-animation {
        animation: color-change 5s infinite;
        font-weight: 400;
    }

    @keyframes color-change {
        0% {
            color: #00FFA3;
        }
        25% {
            color: yellow;
        }
        50% {
            color: #DC1FFF;
        }
        75% {
            color: #F1A945;
        }
        100% {
            color: #00FFA3;
        }
    }
</style>
Share:

Wednesday, January 5, 2022

How to create copy to clipboard in Vuetify VujeJs application

This is a quick tutorial on how we can add copy to clipboard functionality in the VueJs application.

In this example, we are going to create the invitation code where users can copy that code in the clipboard so that they can share it simply by copy-paste.

Let's create a simple component called CopyToClipBoard.vue and add a template

<template>
    <div>
        <v-card height="460" class="mt-8">
            <v-card-title class="justify-center mb-2 pb-0">
                <span class="text-center red--text">Your invite code</span>
            </v-card-title>
            <v-card-text class="text-center mb-0 pb-0">
                <v-chip color="grey" text-color="white" class="font-weight-bold">
                    <span class="inv-text">A0xU76E</span>
                    <v-divider
                            class="mx-4"
                            vertical
                            light
                    ></v-divider>
                    <v-tooltip top>
                        <template v-slot:activator="{ on, attrs }">
                  <span @click="copyCode" @mouseout="reset" style="cursor: pointer;" v-bind="attrs"
                        v-on="on">Copy</span>
                        </template>
                        <span>{{copyText}}</span>
                    </v-tooltip>
                </v-chip>
            </v-card-text>
        </v-card>
    </div>
</template>
Here, we are using vuetify UI framework, you can use your own HTML CSS. We are adding two events called @click for copy text to clipboard and @mouseout event for resetting the default value. 

Let's add the data:
created() {
    this.copyText = this.text
  },
data () {
    return {
      invitationCode:"A0xU76EJK",
      text: "Copy to invite",
      copyText: ''
    }
  },
Create the methods used in template:
methods : {
    async copyCode() {
      await navigator.clipboard.writeText(this.invitationCode);
      this.copyText = "Copied"
    },
    reset() {
      this.copyText = this.text
    }
  }
}
We are using vuetify tooltip to give the copy information. 

When the user clicks on the button it will call copyCode function and will copy in clipboard. In order to do so, we are using navigator.clipboard API which allows user to grant the website or app permission to access the clipboard. 

After that, we have to copy the invitationCode value so we pass this value as a parameter.

The sample demo looks like below:



The overall implementation looks as:
<template>
    <div>
        <v-card height="460" class="mt-8">
            <v-card-title class="justify-center mb-2 pb-0">
                <span class="text-center red--text">Your invite code</span>
            </v-card-title>
            <v-card-text class="text-center mb-0 pb-0">
                <v-chip color="grey" text-color="white" class="font-weight-bold">
                    <span class="inv-text">A0xU76E</span>
                    <v-divider
                            class="mx-4"
                            vertical
                            light
                    ></v-divider>
                    <v-tooltip top>
                        <template v-slot:activator="{ on, attrs }">
                  <span @click="copyCode" @mouseout="reset" style="cursor: pointer;" v-bind="attrs"
                        v-on="on">Copy</span>
                        </template>
                        <span>{{copyText}}</span>
                    </v-tooltip>
                </v-chip>
            </v-card-text>
        </v-card>
    </div>
</template>

<script>
    export default {
        name: "CopyToClipBoard",
        data () {
            return {
                invitationCode:"A0xU76EJK",
                text: "Copy to invite",
                copyText: ''
            }
        },
        created() {
            this.copyText = this.text
        },
        methods : {
            async copyCode() {
                await navigator.clipboard.writeText(this.invitationCode);
                this.copyText = "Copied"
            },
            reset() {
                this.copyText = this.text
            }
        }
    }
</script>

<style scoped>
    .inv-text {
        min-width: 150px;
        font-size: 20px;
    }
</style>
Share:

Tuesday, January 4, 2022

How to install icon fonts in vuetify vue application

This is a quick tutorial on how we can install icon fonts for material icons and font awesome

Although vuetify uses material design icons, that might not be sufficient all the time so we need to use some other library for it.

We can simply install a font by including the specified icon library CDN. For this, go to the project directory and inside it, you can see the index.html file under the public folder.  


Here, add the material icons and font awesome icon CDN link as below.

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900">
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.x/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css">
After adding this, we can simply use icons for e.g: 

From font awesome, simply use the fa- prefixed on icon name:
<v-icon left color="blue" size="50">fa-twitter</v-icon>
For google fonts, go to the google font and click the icon, we can see the icon font name similar as below, simply use the name.
<v-icon left color="blue" size="50">logout</v-icon>
Share:

How to implement social media share buttons in Vue.js

In this tutorial, we are going to implement the social media share button using Vue.js.

Here, we are using the dependency called vue-socials which is very handy while implementing social media share buttons. It contains almost all the social share button functionality that we need and is lightweight and highly customizable.

In this tutorial, we are going to implement the Facebook and Twitter share button as an example. 


Install Dependency:

Go to your project directory and install the dependency.

If you are using the npm package manager

For Vue 2: 
npm install vue-socials
For Vue 3:
npm install vue-socials@next

If you are using the yarn package manager
# Vue 2
yarn add vue-socials

# Vue 3
yarn add vue-socials@next

Now, it's time to import the required share button components. Here we are creating the SocialMediaShare.vue component for demo. 

Inside this component, we are going to import the Facebook and Twitter share button component as below:
import { SFacebook, STwitter } from 'vue-socials'
Now, we need to register the components
  components: { SFacebook, STwitter }
After component registration, let us use it into the template
<div >
    <s-facebook
            :window-features="windowFeatures"
            :share-options="facebookShareOptions"
            :use-native-behavior="useNativeBehavior"
            @popup-close="onClose"
            @popup-open="onOpen"
            @popup-block="onBlock"
            @popup-focus="onFocus"
            style="text-decoration:none"
    >
        <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                aria-hidden="true"
                focusable="false"
        >
            <path d="M9 8h-3v4h3v12h5v-12h3.642l.358-4h-4v-1.667c0-.955.192-1.333 1.115-1.333h2.885v-5h-3.808c-3.596 0-5.192 1.583-5.192 4.615v3.385z"/>
        </svg>
    </s-facebook>
    <s-twitter
            :window-features="windowFeatures"
            :share-options="twitterShareOptions"
            :use-native-behavior="useNativeBehavior"
            @popup-close="onClose"
            @popup-open="onOpen"
            @popup-block="onBlock"
            @popup-focus="onFocus"
            style="text-decoration:none"
    >
        <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                aria-hidden="true"
                focusable="false"
        >
            <path
                    d="M24 4.557c-.883.392-1.832.656-2.828.775 1.017-.609 1.798-1.574 2.165-2.724-.951.564-2.005.974-3.127 1.195-.897-.957-2.178-1.555-3.594-1.555-3.179 0-5.515 2.966-4.797 6.045-4.091-.205-7.719-2.165-10.148-5.144-1.29 2.213-.669 5.108 1.523 6.574-.806-.026-1.566-.247-2.229-.616-.054 2.281 1.581 4.415 3.949 4.89-.693.188-1.452.232-2.224.084.626 1.956 2.444 3.379 4.6 3.419-2.07 1.623-4.678 2.348-7.29 2.04 2.179 1.397 4.768 2.212 7.548 2.212 9.142 0 14.307-7.721 13.995-14.646.962-.695 1.797-1.562 2.457-2.549z"
            />
        </svg>
    </s-twitter>
</div>
We are using some random SVG for icons, we can use the images or custom icons. 




Let's create the data and methods:
data () {
    return {
      windowFeatures: {},
      facebookShareOptions: {
        url: 'https://github.com/',
        quote: 'Quote',
        hashtag: '#Github',
      },
      twitterShareOptions: {
        url: 'https://github.com/',
        text: 'Hello world',
        hashtags: ['hash', 'tag'],
        via: 'twitterdev',
      },
      useNativeBehavior: false,
    }
  },
  methods:{
    onClose() {},
    onOpen() {},
    onBlock() {},
    onFocus() {},
  }

If we run the application we can see something like this:


Click on icons, we can share the content on those social media. We can change the content from data in component. 

For now, we are using the Github link and dummy text as examples.

If we want to import all the share buttons available then import all components as below inside main.js file.
 // Vue 2
import Vue from 'vue'
import VueSocials from 'vue-socials';

Vue.use(VueSocials)

// Vue 3

import { createApp } from 'vue'
import VueSocials from 'vue-socials';
import App from './App.vue'

const app = createApp(App)
app.use(VueSocials)
The overall implementation of the above example looks as below:
<template>
    <div >
        <s-facebook
                :window-features="windowFeatures"
                :share-options="facebookShareOptions"
                :use-native-behavior="useNativeBehavior"
                @popup-close="onClose"
                @popup-open="onOpen"
                @popup-block="onBlock"
                @popup-focus="onFocus"
                style="text-decoration:none"
        >
            <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                    aria-hidden="true"
                    focusable="false"
            >
                <path d="M9 8h-3v4h3v12h5v-12h3.642l.358-4h-4v-1.667c0-.955.192-1.333 1.115-1.333h2.885v-5h-3.808c-3.596 0-5.192 1.583-5.192 4.615v3.385z"/>
            </svg>
        </s-facebook>
        <s-twitter
                :window-features="windowFeatures"
                :share-options="twitterShareOptions"
                :use-native-behavior="useNativeBehavior"
                @popup-close="onClose"
                @popup-open="onOpen"
                @popup-block="onBlock"
                @popup-focus="onFocus"
                style="text-decoration:none"
        >
            <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                    aria-hidden="true"
                    focusable="false"
            >
                <path
                        d="M24 4.557c-.883.392-1.832.656-2.828.775 1.017-.609 1.798-1.574 2.165-2.724-.951.564-2.005.974-3.127 1.195-.897-.957-2.178-1.555-3.594-1.555-3.179 0-5.515 2.966-4.797 6.045-4.091-.205-7.719-2.165-10.148-5.144-1.29 2.213-.669 5.108 1.523 6.574-.806-.026-1.566-.247-2.229-.616-.054 2.281 1.581 4.415 3.949 4.89-.693.188-1.452.232-2.224.084.626 1.956 2.444 3.379 4.6 3.419-2.07 1.623-4.678 2.348-7.29 2.04 2.179 1.397 4.768 2.212 7.548 2.212 9.142 0 14.307-7.721 13.995-14.646.962-.695 1.797-1.562 2.457-2.549z"
                />
            </svg>
        </s-twitter>
    </div>
</template>

<script>
    import { SFacebook, STwitter } from 'vue-socials'

    export default {
        name: "SocialMediaShare",
        components: { SFacebook, STwitter },
        data () {
            return {
                windowFeatures: {},
                facebookShareOptions: {
                    url: 'https://github.com/',
                    quote: 'Quote',
                    hashtag: '#Github',
                },
                twitterShareOptions: {
                    url: 'https://github.com/',
                    text: 'Hello world',
                    hashtags: ['hash', 'tag'],
                    via: 'twitterdev',
                },
                useNativeBehavior: false,
            }
        },
        methods:{
            onClose() {},
            onOpen() {},
            onBlock() {},
            onFocus() {},
        }
    }
</script>
Check out for other share button lists, usage, and demo from these links.

Share:

Friday, January 1, 2021

Adding PWA support in existing VueJs application

In this tutorial, we are going to add the PWA support in the existing VueJs application.

1. Install Vue CLI

npm install -g @vue/cli
# OR
yarn global add @vue/cli

2. Add PWA in our application

Let's open the terminal or command prompt and go to the project directory and add PWA  to the project.
vue add pwa
This will add a couple of files and settings for PWA in our existing application.

1. registerServiceWorker.js under ./src directory.



/* eslint-disable no-console */

import { register } from 'register-service-worker'

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.\n' +
        'For more details, visit https://goo.gl/AFskqB'
      )
    },
    registered () {
      console.log('Service worker has been registered.')
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    updatefound () {
      console.log('New content is downloading.')
    },
    updated () {
      console.log('New content is available; please refresh.')
    },
    offline () {
      console.log('No internet connection found. App is running in offline mode.')
    },
    error (error) {
      console.error('Error during service worker registration:', error)
    }
  })
}
Inside this file, the service worker is registered, and also, we can see the different hooks implemented which we can use in different cases like when the update is found in the app when the user is offline etc.

2. Dependencies added

Under package.json you can see the register-service-worker and PWA plugin is added.


3. Added some icons

Under public/img/icons/ folder some icons are added for mobile, desktop display. Make sure to change your icons for different devices. For more detail on changing this follow the following article.


If you want to configure via config file follow this guide.

Besides this, registerServiceWorker is imported inside main.js file.

3. Build and Deploy the application.

Build and deploy the application, you can see the service worker is activated and running.


You can see the cached file inside cache storage.

By default, it uses default mode which means a service worker is generated for us. If you want to customize it follow the following articles.


To notify the users about the app update follow the following post.


Share: