๐Ÿ“š 3 Simple Vue3 Tips ๐Ÿ“š

๐Ÿ“š 3 Simple Vue3 Tips ๐Ÿ“š

Personal tips

ยท

5 min read

It has been almost a year that I have been working with the VueJs framework. Coming from a ReactJs Background, I had some fear about using a new Framework. Especially since I only knew Vue2 and found the syntax quite unpleasing. I can now strongly suggest to anyone that hesitate between these two framework to choose Vue 3 as it has been a very pleasant and sometimes quite frustrating experience.
I've put into this article some tips ( rookie mistakes ) to use to keep your code neat and maintainable.

GitHub Repository
Online Demo

Let's start!


1.Keep it simple

GitHub Repository

One of the most important concepts as a developer is to avoid code repetition, it's known as the DRY concept. It means that to maintain debug code you should avoid repeating code by instead putting it into a function and calling it instead of rewriting it.
The same principles can occur inside your vue component.

Let's take a concrete example.
We have a page with a button buried deep inside a layer of a component.
We want to know when this button is clicked to inform the user through a toast for example.

Let's dive in!

We have the three following components :

I have put up a simple story where a GrandFather a father and a son pass each other a ball. The order is simple it goes from the older to the younger then the younger passes it to the older.

This allows us to show how to pass data through components.

So it goes as this:

  • GPComponent = GrandFather

  • PComponent = Father

  • CComponent = Child Component

Here is the code of GPComponent:

<template>
    <h4>Grand-Parent Component ๐Ÿ‘ด</h4>
    <button @click="throwBall">pass</button>
    <div v-if="isThrowed">
        <h5>๐Ÿ™Œ ๐Ÿ€</h5>
    </div>
    <PComponent :key="rerender" :ball="ball" @pass="receiveBall" />
</template>
<script setup lang="ts">
import { ref } from 'vue';
import PComponent from './PComponent.vue';
let ball = ref('');
let rerender = ref(0);
let isThrowed = ref(true);
const throwBall = () => {
    ball.value = '๐Ÿ€';
    isThrowed.value = false;
    rerender.value++;
}
const receiveBall = () => {
    ball.value = '';
    isThrowed.value = true;
    rerender.value++;
}
</script>

This component has three key assets, he can throw the ball to pass it through the props.
He passes the ball through the props and receives it through the event.

Then the PComponent code is like this:

<template>
    <h5>Parent Component ๐Ÿ‘จ</h5>
    <button @click="throwBall">pass</button>
    <div v-if="ball && !passedBall">
        <h6>๐Ÿ™Œ {{ ball }}</h6>
    </div>
    <CComponent :ball="passedBall" @pass="emitEvent" />
</template>
<script setup lang="ts">
import { ref } from 'vue';
import CComponent from './CComponent.vue';
const passedBall = ref('');
const emit = defineEmits(['pass'])
defineProps({
    ball: {
        type: String,
        default: '๐Ÿ€'
    }
})
const throwBall = () => {
    passedBall.value = '๐Ÿ€';
}
const emitEvent = (value: string) => {
    console.log(value);
    emit('pass', value)
}
</script>

Then the Child Component :

<template>
    <h6>Child Component  </h6>
    <div v-if="ball && !passedBall">
        <h6>๐Ÿ™Œ {{ball}}</h6>
    </div>
    <button @click="throwBall">pass</button>
</template>

<script setup lang="ts">
import { ref } from 'vue';

const  emit = defineEmits(['pass'])
 const props = defineProps({
    ball:{
        type:String,
        default:'๐Ÿ€'
    }
})
const passedBall = ref(props.ball ?? '');
const throwBall = () => {
    passedBall.value = '๐Ÿ€';
    emit('pass',passedBall.value)
}
</script>

2.Unleash the power of template

GitHub Repository

It's a very simple tip but I will mention them nevertheless. For clearer code when iterating on a list, I strongly suggest you put it inside a template rather than directly on the element like so.

<template>
    <div class="weird-row">
       <template v-for="item in data" :key="item">
            <div class="weird-row__item">
                {{ item }}
            </div>
        </template>
        <button class="weird-row__item">Hi !</button>
    </div>
</template>

Another tip when iterating is to use the v-slot mechanism as it works on the list too and it's pretty useful as I demonstrated in the second tips folder inside the repository.

It allows you to make the component more reusable because once you have your list that iterates the slot and passes in the data you can plug virtually any component.

We have a WeirdList a Weird Table and a WeirdRow and we want each component to be able to work with some other component here is how to proceed.

Here is the WeirdTable Component :

<template>
    <div class="weird-table">
        <template v-for="data in datas" :key="data.id">
            <slot name="item" v-bind="{ ...data }" />
        </template>
    </div>
</template>
<script setup lang="ts">
import { PropType } from 'vue';
defineProps({
    datas: {
        type: Array as PropType<any[]>,
        required: true
    }
})
</script>

Here our slot will contain any component that we choose to pass in when using this component.

<template>
    <div class="weird-header">
        <template v-for="item in headers" :key="item">
            <div class="weird-header__item">
                {{ item }}
            </div>
        </template>
    </div>
    <WeirdTable :datas="datas" >
        <template
        #item="{
          id,name,age
        }"
      >
      <WeirdRow :data="{ id,name,age }" />  
    </template>
    </WeirdTable>
</template>

<script setup lang="ts">
import WeirdTable from './WeirdTable.vue';
import WeirdRow from './WeirdRow.vue';
const headers = [...]
const datas = [...]
</script>

We pass in our #item template as will be replaced by vue by our component and we can choose which data we can pick from our object which is inside our data array.
We can pass it into our weird row as props.
This is super useful and has been a lifesaver recently.


3.Array to display

GitHub Repository

In a Vue App, you will probably be fetching data from apis ans will display it.

Two cases might happen:
case 1: You have a graphQl API and you can choose which data you receive.
case 2: You have an API that sends you a load of useless data and you want to display a bunch of things.

If you are in the second case you might put your array inside a v-for and put v-if on the data that you do not want to display.
Inside a v-for list, Vue renders your v-list without the v-if then he renders again reading the v-if which could lead to major performance issues.
I suggest making a displayable array as you might need some other resources from your API call.

Instead of doing this:

<template>
    <div class="comment-card">
        <div v-for="info in comment" >
        <p v-if="!info.toString().endsWith('.com')">{{ info }}</p>
        </div>
    </div>
</template>

You should filter the comment array and remove the info that ends with '.com'.


Thank you for reading me I hope I will post more regularly and comments are always welcome!
See you next time!

Did you find this article valuable?

Support nass.bin by becoming a sponsor. Any amount is appreciated!

ย