Categories
Vue 3 Projects

Create a Coin Flip 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 coin flip 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 coin-flip

and select all the default options to create the project.

Create a Coin Flip App

To create the coin flip app, we write:

<template>
  <div>
    <h1>select a face</h1>
    <button @click="selectedFace = 'heads'">heads</button>
    <button @click="selectedFace = 'tails'">tails</button>
  </div>
  <p>you selected: {{ selectedFace }}</p>
  <p>computer selected: {{ computerSelectedFace }}</p>
  <button @click="flip">flip coin</button>
  <p v-if="isWin">you win</p>
  <p v-else>you lost</p>
</template>

<script>
const faces = ["heads", "tails"];
export default {
  name: "App",
  data() {
    return {
      selectedFace: "",
      coinFlipResult: "",
    };
  },
  computed: {
    computerSelectedFace() {
      const { selectedFace } = this;
      const face = faces.find((f) => f !== selectedFace);
      return face;
    },
    isWin() {
      const { selectedFace, coinFlipResult } = this;
      return coinFlipResult === selectedFace;
    },
  },
  methods: {
    flip() {
      let index;
      if (Math.random() < 0.5) {
        index = 0;
      } else {
        index = 1;
      }
      this.coinFlipResult = faces[index];
    },
  },
};
</script>

In the template, we have a heads button to let the player select heads.

And we have another button to lets the player select tails.

Once a button is clicked, the selectedFace value is set.

Then we have the p elements to show the selected coin face of the player and the computer.

Next, we add a flip coin button to let us flip the coin.

Then we display if the player won or lost in the p elements.

Next, in the script tag, we have the faces array with the 'heads' and 'tails' strings.

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

Next, we have the computed properties.

We have the computedSelectedFace which returns the coin face that the computer chooses, which is the one the player didn’t choose.

isWin checks if coinFlipResult is the same as seletedFace , which indicates that the player wins.

And finally, we have the flip method to set coinFlipResult to set the coin flip result.

Conclusion

We can create a coin flip app easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Welcome Message 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 welcome message 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 welcome-message

and select all the default options to create the project.

Create a Welcome Message App

To create the welcome message app, we write:

<template>
  <form @submit.prevent="submit">
    <div>
      <label>first name</label>
      <input v-model.trim="firstName" />
    </div>
    <div>
      <label>last name</label>
      <input v-model.trim="lastName" />
    </div>
    <button type="submit">submit</button>
  </form>
  {{ message }}
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      firstName: "",
      lastName: "",
      message: "",
    };
  },
  computed: {
    formValid() {
      const { firstName, lastName } = this;
      return firstName.length > 0 && lastName.length > 0;
    },
  },
  methods: {
    submit() {
      if (!this.formValid) {
        return;
      }
      const { firstName, lastName } = this;
      this.message = `hello, ${firstName} ${lastName}`;
    },
  },
};
</script>

We have the form with 2 input fields.

One is for entering the first name and one is for entering the last name.

To bind the input values to reactive properties, we have the v-model directive.

The trim modifier lets us trim the starting and trailing whitespace from the entered value.

To listen to the submit event, we have the @submit directive on the form.

The prevent modifier lets us prevent server-side submission and do client-side submission.

In the component object, we have the data method to return an object with the reactive properties and their initial values.

Next, we add the formValid computed property to check if firstName and lastName have lengths bigger than 0.

Then finally, we add the submit method that checks if formValid is true .

If it is, then we proceed to set the message reactive property to the welcome message string.

Then message is displayed below the form in the template.

Conclusion

We can create a welcome message app with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Hangman Game 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 hangman game 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 hangman

and select all the default options to create the project.

Create a Hangman Game

To create the hangman game, we write:

<template>
  <div v-if="isWin">
    you win
    <button type="button" @click="reset">reset</button>
  </div>
  <div v-else>
    <div v-if="guessesLeft > 0">
      <p>guesses left: {{ guessesLeft }}</p>
      <form @submit.prevent="guess">
        <div>
          <label>guess</label>
          <input v-model.trim="guessLetter" />
        </div>
        <button type="submit">guess</button>
      </form>

      <span v-for="(l, index) of lettersToShow" :key="index">
        {{ l }}
      </span>
    </div>
    <div v-else>
      you lost
      <button type="button" @click="reset">reset</button>
    </div>
  </div>
</template>

<script>
const answer = "hangman";

export default {
  name: "App",
  data() {
    return {
      guessLetter: "",
      answer,
      guesses: [],
    };
  },
  computed: {
    formValid() {
      const { guessLetter } = this;
      return /[a-z]{1}/.test(guessLetter);
    },
    lettersToShow() {
      const { answer, guesses } = this;
      return answer.split("").map((a) => {
        if (guesses.includes(a)) {
          return a;
        }
        return "_";
      });
    },
    guessesLeft() {
      const { answer, guesses } = this;
      return (
        6 -
        guesses.filter((g) => {
          return !answer.includes(g);
        }).length
      );
    },
    isWin() {
      const { answer, guesses } = this;
      const includedLetters = guesses.filter((g) => {
        return answer.includes(g);
      });
      return answer.split("").every((a) => {
        return includedLetters.includes(a);
      });
    },
  },
  methods: {
    guess() {
      if (!this.formValid) {
        return;
      }
      this.guesses.push(this.guessLetter);
      this.guessLetter = "";
    },
    reset() {
      this.guesses = [];
      this.guessLetter = "";
    },
  },
};
</script>

In the template, we check is isWin is true .

If it is, then we show ‘you win’.

And we show the reset button to let the user restart the game.

Otherwise, we show a div with a form to let the player guess letters if guessesLeft is bigger than 0.

This indicates that the player can still guess.

The form has the guess field to let the player enter a letter to guess.

We bind it to guessLetter with v-model .

And we use the trim modifier to trim whitespaces.

We listen to the submit event with the @submit directive and the guess method.

prevent lets us prevent server-side form submission and do client-side submission instead.

Below that, we loop through the letters to show.

Otherwise, we show a ‘you lost’ message to the player since there are no more guesses left.

And we show the reset button on that div to let the player reset the game.

At the top of the script we have the answer variable.

guessLetter has the letter.

guesses has an array of guesses, which are single-letter strings.

We make sure that the input value is a single-letter string with the formValid computed property.

lettersToShow has the letters that are guessed so far.

We return the letter that are guessed corrected if they’re checked to be so with guess.includes(a) .

answers have correct string, so we can check the letters in that with includes to see if we have correct letters.

Otherwise, we return an underscore.

guessesLeft have the number of guesses left.

It’s 6 minus the number of incorrect guesses, which is determined by:

guesses.filter((g) => {
  return !answer.includes(g);
}).length

isWin determines if the player won or not.

We determine this by getting the correct letters that are stored in the includedLetters variable.

And we call every on the answer string split into an array to see if every letter in answer is included in includedLetters .

Now we add the guess method to let the player entered the guess.

We only accept the guess if the form is valid according to the formValid variable.

If that’s true , then we push the guessLetter to this.guesses and reset the value of guessLetter after that.

The reset method resets the guesses and guessLetter values.

Conclusion

We can create a hangman game easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Notes 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 notes 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 notes-app

and select all the default options to create the project.

We also need the uuid package to let us generate unique IDs for our notes.

To do this, we run:

npm i uuid

Create the Notes App

To create the notes app, we write:

<template>
  <form @submit.prevent="add">
    <h1>add note</h1>
    <div>
      <label>title</label>
      <input v-model="title" />
    </div>
    <div>
      <label>description</label>
      <input v-model="description" />
    </div>
    <button type="submit">add</button>
  </form>

  <form>
    <h1>search</h1>
    <div>
      <label>keyword</label>
      <input v-model="keyword" />
    </div>
  </form>

  <div v-for="(note, index) of filteredNotes" :key="note.id">
    <h2>{{ note.title }}</h2>
    <p>{{ note.description }}</p>
    <button type="button" @click="remove(index)">remove</button>
  </div>
</template>

<script>
import { v4 as uuidv4 } from "uuid";

export default {
  name: "App",
  data() {
    return {
      title: "",
      description: "",
      keyword: "",
      notes: [],
    };
  },
  computed: {
    filteredNotes() {
      const { keyword } = this;
      if (!keyword) {
        return this.notes;
      }
      return this.notes.filter(({ title, description }) => {
        return title.includes(keyword) || description.includes(keyword);
      });
    },
  },
  methods: {
    add() {
      const { title, description } = this;
      this.notes.push({
        id: uuidv4,
        title,
        description,
      });
      this.title = "";
      this.description = "";
    },
    remove(index) {
      this.notes.splice(index, 1);
    },
  },
};
</script>

The first form lets us add a note entry.

We have the submit event listener added with the @submit directive.

prevent lets us prevent server-side submission.

The inputs have the v-model directive to let us bind to the reactive properties so we can use them in the component object.

Then we have the submit button with type set to submit to let us submit the form when we click it.

Below that, we have another form to let us search for notes.

We have an input that’s bound to the keyword reactive property with v-model .

And below that, we render the filterNotes into HTML with the v-for directive.

We render the title and description properties.

Also, we need the key prop set to the id property so that it receives a unique ID.

This way, Vue 3 can keep track of the items properly.

In the component object, we have the data method to return an object with the reactive properties with their initial values.

Also, we have the filteredNotes computed property to get the notes filtered by keyword .

Then we add the add method to put the title and description into an object with the id and call this.notes.push to push that into the this.notes array.

The remove method lets us remove an entry by index with splice .

Conclusion

We can create a notes app easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Whack a Mole Game 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 whack a mole game 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 whack-a-mole

and select all the default options to create the project.

Create the Whack a Mole Game

To create the whack a mole game, we write:

<template>
  <button @click="startGame">start game</button>
  <button @click="endGame">end game</button>
  <p>score: {{ score }}</p>
  <div>
    <div v-for="n of 6" :key="n" class="container">
      <img
        v-if="index === n"
        src="https://grid.gograph.com/happy-mole-cartoon-vector-art_gg68718247.jpg"
        @click="onClick(n)"
      />
      <div v-else class="hole"></div>
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      index: 0,
      timer: undefined,
      score: 0,
    };
  },
  methods: {
    generateIndex() {
      this.index = Math.floor(Math.random() * 6);
    },
    startGame() {
      this.timer = setInterval(this.generateIndex, 2000);
    },
    endGame() {
      clearInterval(this.timer);
      this.score = 0;
      this.index = 0;
    },
    onClick(n) {
      if (this.index === n) {
        this.score++;
      }
    },
  },
  beforeUnmount() {
    clearInterval(this.timer);
  },
};
</script>

<style scoped>
.hole {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  border-radius: 50%;
}

.container {
  display: inline-block;
}

img {
  width: 50px;
  height: 50px;
}
</style>

We have the start game and end game buttons to let us start and end the game.

When we click start game, startGame is called to start the game.

And when we click start game, endGame is called to end the game.

Then we show the score to the player in the p element.

Next, we render the divs to show the mole.

index is the index where the mole is located.

So if index equals n , then we show the mole.

Otherwise, we show a circle.

On the image, we have a click event listener that checks if we click on the mole.

In the component object, we have the data method to return the initial values of the reactive properties.

The generateIndex generates random index value.

startGame starts the game by calling setInterval to start the timer.

The 2nd argument is the interval to wait between the callback in the first argument runs again.

The interval is in milliseconds.

endGame calls clearInterval to the end of the timer.

We also set score and index back to 0 to reset the game.

The onClick method checks if n is the same as this.index and increases the score if it is.

Now when we click start game, we should see moles popping up and we can click it to increase the score.

Conclusion

We can create a whack a mole game easily with Vue 3 and JavaScript.