Categories
Vue 3 Projects

Create a Countdown Timer App with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a countdown timer app with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create digital-clock

and select all the default options to create the project.

Create the Countdown Timer App

To create the countdown timer, we write:

<template>
  <p>
    {{ diff.year }} years, {{ diff.month }} months, {{ diff.day }} days,
    {{ diff.hour }} hours, {{ diff.minute }} minute, {{ diff.second }} seconds
    until
    {{ formatDate(futureDate) }}
  </p>
</template>

<script>
const futureDate = new Date(2050, 0, 1);
const getDateDiff = (date1, date2) => {
  const diff = new Date(date2.getTime() - date1.getTime());
  return {
    year: diff.getUTCFullYear() - 1970,
    month: diff.getUTCMonth(),
    day: diff.getUTCDate() - 1,
    hour: diff.getUTCHours(),
    minute: diff.getUTCMinutes(),
    second: diff.getUTCSeconds(),
  };
};
export default {
  name: "App",
  data() {
    return {
      futureDate,
      diff: {},
      timer: undefined,
    };
  },
  methods: {
    getDiff() {
      this.diff = getDateDiff(new Date(), futureDate);
    },
    formatDate(date) {
      let d = new Date(date),
        month = (d.getMonth() + 1).toString(),
        day = d.getDate().toString(),
        year = d.getFullYear().toString();

      if (month.length < 2) month = "0" + month;
      if (day.length < 2) day = "0" + day;

      return [year, month, day].join("-");
    },
  },
  beforeMount() {
    this.timer = setInterval(this.getDiff, 1000);
  },
  beforeUnmount() {
    clearInterval(this.timer);
  },
};
</script>

In the template, we display the date and time diff parts and the date we’re counting down towards.

Then in the script tag, we have the futureDate to count down to.

getDateDiff lets us get the date difference.

We get the date difference by subtracting the UNIX timestamp version of date2 and date1 .

We get the timestamp with getTime .

Then we get the parts of the date difference wirthr the built in Date instabnce methods.

getUTCFullYear gets the number of years in the diff .

We subtract that by 1970 to get the year of the diff .

getUTCMonth returns the number of months of the diff .

getUTCDate returns the number of days of the diff .

getUTCHours returns the number of hours of the diff .

getUTCMinutes returns the number of minutes of the diff .

getUTCSeconds returns the number of seconds of the diff .

We pass in the futureDate into the object we return with data so we can use it in the template.

getDiff calls getDateDiff to get the difference between the current date time and futureDate .

formatDate lets us format the futureDate to yyyy-mm-dd format.

We do this by getting the month with getMonth .

We use getDate to get the number of days.

And we ye getFullYear to get the number of years.

If month and day have less than 2 digits, then we add a 0 before the month and day strings.

Then in the beforeMount hook, we call setInterval with getDiff to compute the date difference between the current date time and futureDate .

setInterval calls the callback in the first argument periodically.

1000 is the interval in milliseconds we wait before calling the getDiff method again.

We assign the returned timer object to this.timer .

Then we call clearInterval in beforeUnmount to clear the timer when we unmount the component.

Conclusion

We can create a countdown timer easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Digital Clock App with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a digital clock app with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create digital-clock

and select all the default options to create the project.

Create the Digital Clock App

We can create a digital clock app with the following code:

<template>
  <div>{{ dateTime.hours }}:{{ dateTime.minutes }}:{{ dateTime.seconds }}</div>
</template>

<script>
const date = new Date();
export default {
  name: "App",
  data() {
    return {
      dateTime: {
        hours: date.getHours(),
        minutes: date.getMinutes(),
        seconds: date.getSeconds(),
      },
      timer: undefined,
    };
  },
  methods: {
    setDateTime() {
      const date = new Date();
      this.dateTime = {
        hours: date.getHours(),
        minutes: date.getMinutes(),
        seconds: date.getSeconds(),
      };
    },
  },
  beforeMount() {
    this.timer = setInterval(this.setDateTime, 1000);
  },
  beforeUnmount() {
    clearInterval(this.timer);
  },
};
</script>

In the template, we display the hours, minutes, and seconds with dateTime.hours , dateTime.minutes and dateTime.seconds respectively.

In the data method, we return the dateTime object with the hours , minutes , and seconds property.

new Date() returns an object the current date and time.

getHours returns the hour of the date.

getMinutes returns the minutes of the date.

getSeconds returns the seconds of the date.

In the setDateTime method, we get the current date with new Date() .

And we call getHours , getMinutes , and getSeconds to get the time parts.

In the beforeMount hook, we call setInterval with the this.setDateTime method to run it every second.

The 2nd argument specifies that it runs every 1000 milliseconds, which is 1 second.

It returns the timer object which we assign to the timer reactive property.

beforeMount runs when the component is mounting.

beforeUnmount calls the clearIntrval method with the timer reactive property to clear the timer when the component unmounts.

In the template, we show the time and it updates every second.

Conclusion

We can create a digital clock easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Background Color Switcher App with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a background color switcher app with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create background-switcher

and select all the default options to create the project.

Create the Background Color Switcher App

To create the background color switcher app, we create 4 circles.

When we click on a circle, the background color switches to the background color of the circle we clicked on.

To do this, we write:

<template>
  <div id="screen" :style="{ 'background-color': backgroundColor }">
    <div
      v-for="c of colors"
      :key="c"
      :style="{
        'background-color': c,
      }"
      class="circle"
      @click="backgroundColor = c"
    ></div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      colors: ["red", "green", "blue", "yellow"],
      backgroundColor: undefined,
    };
  },
  methods: {},
};
</script>

<style>
.circle {
  border-radius: 50%;
  width: 50px;
  height: 50px;
  border: 1px solid black;
  display: inline-block;
  cursor: pointer;
}

#screen {
  width: 100vw;
  height: 100vh;
}
</style>

We have the colors reactive property array that we use to render into circles with v-for in the template.

We set the background color each circle with the style prop.

The key prop is set to the color, which is the unique ID of the array.

We add a click listener to each circle to set the backgroundColor to the color c .

The div with ID screen is has the style prop to set the background-color CSS property to the backgroundColkor reactive property.

In the style tag, we make the divs with class circle circles by setting the border-radius to 50%.

Width and height are set to 50px.

border is set to a black border 1px thick.

display is set to inline-block to make the divs display side by side.

cursor is set to pointer so that we see the hand when we hover over the div.

Now when we click on the circles, we see the color changes as we click on the circle.

Conclusion

We can create a background color switcher app easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Quote of the Day App with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a quote of the day app with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create quote-of-the-day-app

and select all the default options to create the project.

Create the Quote of the Day App

We can create our quote of the day app by writing:

<template>
  <button @click="getRandomQuote">get quote</button>
  <p>{{ quoteOfTheDay }}</p>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      quotes: [],
      quoteOfTheDay: "",
    };
  },

  methods: {
    async getQuotes() {
      const res = await fetch(`https://type.fit/api/quotes`);
      const quotes = await res.json();
      this.quotes = quotes;
    },
    getRandomQuote() {
      const index = Math.floor(Math.random() * this.quotes.length);
      const quoteOfTheDay = this.quotes[index];
      this.quoteOfTheDay = quoteOfTheDay.text;
    },
  },
  async beforeMount() {
    await this.getQuotes();
    this.getRandomQuote();
  },
};
</script>

In the component object, we have the data method to return an object with the quotes and qyoteOfTheDay reactive properties.

quotes have an array of quotes.

quoteOfTheDay has the quote picked randomly from the quotes array.

In the methods property, we have the getQuotes method that calls fetch to get the quotes from the URL.

Then we call res.json() to get the JSON from the response.

Each line returns a promise, so we need to add await to wait for each line to return the result.

And then we assign the quotes JSON array to thre this.quotes reactive property.

getRandomQuotes randomly generates the index of the quotes array.

Then we set the quoteOfTheDay to get the route.

And then we can the text property to get the quote text.

In the beforeMount hook, we run the getQuotes method and getRandomQuote method to get the quote.

beforeMount is run when the component mounts, so we’ll get the quotes when the component loads.

In the template, we have a button to get the quote with getRandomQuote and we display the result in the p element.

Conclusion

We can create a quote of the day app easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Loan Calculator App with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a loan calculator app with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create loan-calculator

and select all the default options to create the project.

Create the Loan Calculator App

We can create our loan calculator app by writing:

<template>
  <form @submit.prevent="calculate">
    <div>
      <label>loan amount</label>
      <input v-model.number="loanAmount" />
    </div>
    <div>
      <label>interest rate</label>
      <input v-model.number="interestRate" />
    </div>
    <div>
      <label>number of months to pay off loan</label>
      <input v-model.number="numMonths" />
    </div>
    <button type="submit">calculate monthly payment</button>
  </form>
  <p>monthly payment: {{ monthlyPayment.toFixed(2) }}</p>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      loanAmount: 0,
      interestRate: 0,
      numMonths: 0,
      monthlyPayment: 0,
    };
  },
  computed: {
    formValid() {
      const { loanAmount, interestRate, numMonths } = this;
      return (
        +loanAmount >= 0 &&
        0 <= +interestRate &&
        +interestRate <= 100 &&
        +numMonths > 0
      );
    },
  },
  methods: {
    calculate() {
      if (!this.formValid) {
        return;
      }
      const { loanAmount, interestRate, numMonths } = this;
      this.monthlyPayment = (loanAmount * (1 + interestRate / 100)) / numMonths;
    },
  },
};
</script>

We create a form with the loan amount, interest rate, and the number of months to pay off loan fields.

They all bind to a reactive with the v-model directive.

And they all have the number modifier to automatically convert the inputted value to a number.

We also have the submit button to let us trigger the submit event to run the calculate method.

prevent lets us prevent the default server-side submission behavior.

The data method returns an object with the reactive properties and their initial values.

We also have the formValid computed property to return the condition where the form is valid.

loanAmount must be 0 or larger.

interestRate must be between 0 and 100.

And numMonths must be bigger than 0.

We use the + sign to let us convert them to numbers easily.

And the calculate method checks the formValid computed property to see if the form is valid.

And then makes the calculation for the monthly payment with the last line of the method.

In the template, we display the monthly payment rounded to 2 decimal places.

The toFixed method does the rounding and returns the string form of the value.

Conclusion

We can create a loan calculator with Vue 3 and JavaScript.