Categories
Vue 3 Projects

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *