My first Vue3 component

My first Vue3 component
I like to work with Vuejs, and today I tried to use the next version of Vuejs: Vue3. My first question was: how can I create a new Web Application with Vue3 and the right npm dependencies?

I like to work with Vuejs, and today I tried to use the next version of Vuejs: Vue3.

My first question was: how can I create a new Web Application with Vue3 and the right npm dependencies?

To do that, I used Vite as build tool. Vite is an amazing web dev build tool that serves your code via native ES Module imports during dev and bundles it with Rollup for production. Vite uses Vue3. So if we use Vite we have an amazing fast build tool and we have all vue3 dependencies ready to use.

Install the skeleton for Vue 3

In order to install Vite and your sample application based on Vue3:

npm init vite-app rollthedice
cd rollthedice
npm i
npm run dev

Now you can open your browser at: http://localhost:3000/

Image for post

The demo application made with Vue 3.0 and Vite

Yes, you are running a Vue3 web application.

Roll the dice web application

Now I would like to create a very simple “Roll the Dice” web application.

The user can click a button in order to generate a random number (from 1 to 6) and update the text where the result is shown and the list of the previous rolls. Very simple but useful to walk through on the basic stuff of Vue3, start to understand the main differences with Vue2 and look at the CompositionAPI.

So now let’s jump on the code.

The Code

The command “npm init vite-app rollthedice” created for you a basic skeleton of Vue3 web application. Now we will focus on 2 files.

  • src/App.vue: where your component is loaded
  • src/components/RollTheDice.vue: is the file that we will create from scratch with the template and the logic of our component (the button, the labels, the function that generates a random number). By default our skeleton provide a HelloWorld.vue basic component. My suggestion for you, is to take a look on this file, just to understand the structure. You will not see so much differences with Vue2. Now, create a new empty file RollTheDice.vue, where we will test and try some basic functionalities of Vue3.

Image for post

The basic structure of your Vue3 web application

The src/App.vue file

The main goal of App.vue file is to load the component.

<template>
<!-- ##001: use the component in template -->
  <RollTheDice />
</template>
<script>
// ##002: import the component
import RollTheDice from './components/RollTheDice.vue'
export default {
  name: 'App',
  components: {
    // ##003: declare the component
    RollTheDice
  }
}
</script>
  • ##001: we are using the component in the template, in this case we don’t need to pass any props to the component so is enough;
  • ##002: import the component;
  • ##003: declare the component

So, as you can see, no differences with Vue2.

Let’s create the new component file: src/components/RollTheDice.vue.

The new src/components/RollTheDice.vue file

The component file is a little be longer than the App.vue.

Let me split in two part. The first one is the template part, where we will use some variables and functions that we will cover in the script section.

So, two part: one is template and the last one is script. Both are included in the same file RollTheDice.vue.

The template

The first part of the file is for the template:

<template>
  <h1>Number is: {{ dice }}</h1>
  <div>Number of rolls: {{ rolls.length }}</div>
  <div>Total: {{ total }}</div>
  <button @click="roll()">Let's roll the dice</button>
  <button @click="restart()">Restart</button>
  <ul>
    <li  v-for="(t, index) in rolls" :key="index">
       {{ t }}
    </li>
  </ul>
</template>

As you can see we are using:

  • some reactive variables : dice, an array rolls (we are using length attribute);
  • a computed function total, computed funciton is to recalculate the value once of the reactive variables (used in the computed function) changes;
  • a couple of functions called by a user action (click on a button): roll() and restart().

The script

<script>
// ##001 : import ref and computed from vue3
import { ref, computed } from "vue";
export default {
  name: 'RollTheDice',
// ##002 : implement setup function
  setup() {
// ##003 : declare and initialize 2 reactive variables dice and rolls
    const dice = ref(0);
    const rolls = ref([]);
// ##004: implement roll function (inside setup() )
    function roll() {
      dice.value = Math.floor(Math.random() * Math.floor(5)) + 1;
      rolls.value.unshift(dice.value);
    }
// ##005: implement restart function (inside setup() )
    function restart() {
      dice.value=0
      rolls.value = [];
    }
// ##006: define a computed function (total)
    const total = computed(() => {
      let temptotal = 0;
      for (let i=0 ; i< rolls.value.length; i++) {
        temptotal = temptotal + rolls.value[i]
      }
      return temptotal;
    });
// ##007: expose to the template all stuff (variables, functions, computed etc)
    return { dice, rolls, total, roll, restart };
  }
}
</script>
  • ##001 import ref and computed from Vue3: we need to import some functionalitiy from Vue3 like ref for declaring variables as reactive and computed for declaring computed function;
  • ##002 setup function: with composition API in Vue3 we need to implement the setup function. Setup function will contain and will return as object (see point ##007) all stuff needed by template;
  • ##003 declare 2 reactive objects dice and rolls. To make them reactive we will “incapsulate” the number and the array in ref objects. So dice is not just a simple integer but it is a ref object. For this reason , later when we will need to access to dice value we will use dice.value. We will do the same for the ref array rolls.
  • ##004 implement the roll() function in order to change the value of dice and adding on top of the array rolls the new dice value (to keep track of all rolls);
  • ##005 implement the restart() function in order to re-initialize dice and rolls (we are accessing to them via value attribute);
  • ##006 define the total computed function. When something will change in rolls array, the total is evaluated again. In the template we can use total computed function as we use the variables;
  • ##007 this is a new thing for Vue2 users (because the setup() method). We need to return an object with all stuff needed in the template.

That’s all for now. So if you have your “npm run dev” you have an hot reload provided by Vite so go to your browser, go to http://localhost:3000/ and take a look your new Vue3 web application.

The result

Image for post

Roll the dice

References

This is a list of useful links:

I’m exploring Vue3 so if you have some feedback, please let me know in the comments. Thank you!

Suggest:

Vue js Tutorial Zero to Hero || Brief Overview about Vue.js || Learn VueJS 2023 || JS Framework

Learn Vue.js from scratch 2018

Is Vue.js 3.0 Breaking Vue? Vue 3.0 Preview!

Vue.js Tutorial: Zero to Sixty

Learn Vue.js from Scratch - Full Course for Beginners

Create Shopping basket page With Vuejs and Nodejs