Categories
Vue 3 Projects

Create a Random Joke 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 random joke 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 joke-app

and select all the default options to create the project.

Create the Random Joke App

We can create our random joke app by writing:

<template>
  <div>
    <p>{{ joke }}</p>
    <button @click="getJoke">get new joke</button>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      joke: "",
    };
  },
  methods: {
    async getJoke() {
      const res = await fetch("https://api.chucknorris.io/jokes/random");
      const data = await res.json();
      this.joke = data.value;
    },
  },
  beforeMount() {
    this.getJoke();
  },
};
</script>

We display the joke value in the p element.

The button lets us get the joke when we click on it

It calls getJoke to get a new joke.

In the getJoke method, we call fetch to get the joke value.

It makes a GET request to get the joke from the URL.

The URL is the Chuck Norris API.

It returns a promise with an object with the json method that returns the JSON object from the response.

Then we get the value property from the JSON object to set the joke reactive property.

In the beforeMount method, we call getJoke so that we display the joke when the page loads.

Conclusion

We can create a random joke 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 *