Vue.js Fundamentals: All You Need to Know about Vue.js

Dhrubok Infotech Services
6 min readJun 7, 2021

--

Vue.js is rapidly growing its popularity because of its lightweight nature. It is highly adoptable and an easy-to-pick-up Javascript Framework to develop the front-end of any WebApp. Any sophisticated Single-Page Application can be easily built when used in combination with modern tooling and supporting libraries. This blog post will help you with all the vue.js fundamentals to get you started.

A general vue page or component structure is like below:

<template>
...
</template>
<script>
export default {
...
}
</script>
<style>
...
</style>

Here, in the <template> section we define HTML codes. Vue.js uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying Vue instance’s data. All Vue.js templates are valid HTML that can be parsed by spec-compliant browsers and HTML parsers.

In the <script> section, logic can be defined, here we work with lifecycle hooks and other vue js features like watchers, computed properties etc.

And in the <style> section, custom css codes can be added. If we want classes or ids to impact only this one component we can use “scoped” syntax.

<style scoped>
...
</style>

Now let’s start from the beginning.

If we define other vue js app like this,

<div id="app">
<p>I have a {{ book }}</p>
<p>{{ isWorking ? 'YES' : 'NO' }}</p>
</div>

Then in Vue js, we no longer have to interact with the HTML directly. A Vue app attaches itself to a single DOM element (#app in our case) then fully controls it. The HTML is our entry point, but everything else happens within the newly created Vue instance.

Here in this Article we will look into the many of the fundamental building blocks of vue js.

  1. Directives
  2. List Rendering
  3. Binding
  4. Actions / Events
  5. Custom Events
  6. Lifecycle Hooks
  7. Slots

Vue.js Directives

Here, Let’s talk about the conditional rendering using v-if, v-else-if, v-else.

<p v-if="isEmpty">{{ book }}</p><p v-else-if="isEmpty">...</p>
<p v-else>...</p>

There is another property “v-show” which can be used to control the display property of CSS.

<p v-show="isEmpty">...</p>

Note, “isEmpty” can be a computed property or a data property or a prop. More on these …

Another very important concept of vue.js fundamentals is data binding. More specifically, two way binding.

Two-way data binding:

<input v-model="firstName" >

Here are few other helping versions:

v-model.lazy=”…” ~ Syncs input after change event

v-model.number=”…” ~ Always returns a number

v-model.trim=”…” ~ Strips whitespace

More on “v-model”

“v-model” works with these properties, called value and input function.
Both of these are same:

<my-input v-model="foo"></my-input>
<my-input :value="foo" @input="foo = $event"></my-input>

For reference, visit this thread from Stack Overflow.

Vue.js List Rendering

List rendering is one of the most basic core requirements.

Here is how it works.

<li v-for="item in items" :key="item.id">
{{ item }}
</li>

Please Note, using “key” is very important and always recommended.

Looping through data is a very common scenario. These data types can be an Array or an Object. Here are few examples:

To iterate through Array:

<li v-for="(item, i) in items" :key="i">
{{item}}
</li>

Index of the array can be easily accessed and that can be used for the “key”.

To iterate through Objects:

<li v-for="(element, i) in object" :key="i">
{{element}}
</li>

The basic syntax and concepts are the same as before.

v-for can also be used on any component with the same syntax style as before.

<cart v-for="(item,i) in books" :key="i"> </cart>

Vue.js Binding

Binding is one of the most important concepts of vue.js fundamentals. We have already seen v-model, however, props can be bound with data.
Here are few data binding example:

<a v-bind:href="url">...</a> or <a :href="url">...</a> [shorthand]

True or false will add or remove attribute:

<button :disabled="isButtonDisabled”>...</button>

If isActive is truthy, the class ‘active’ will appear:

<div :class="{ active: isActive }">...

Style color set to value of activeColor:

<div :class="{ active: isActive }">...

More details can be found here.

Vue.js Events

Now let’s talk about events. Events are also very important for vue js app.

Calls addToCart method on component:

Here is an example of calling a method from a button using “@click”.

<button @click="addToCart">...</button>
<button v-on:click="addToCart">...</button>

We can also pass arguments. Here is an example:

<button @click="addToCart(product)">... </button>

To prevent default behavior (e.g. page reload):

<form @submit.prevent="addProduct">... </form>

Only trigger once:

<img @mouseover.once="showImage">... </img>

Here are few other usable properties to use with method calling.

.stop

Stop all event propagation

.self

Only trigger if event.target is element itself.

Now, let’s talk about method calling using keyboard press.

Keyboard entry example:

<input @keyup.enter="submit">

Call onCopy when control-c is pressed:

<input @keyup.ctrl.c="onCopy">

Other Key modifiers:

.tab .delete .esc .space .up .down .left .right .ctrl .alt .shift .meta

Mouse modifiers

.left .right .middle

Component Anatomy

Vue.component('my-component', {
components: { [ Components that can be used in the template ]
ProductComponent, ReviewComponent
},
props: { [The parameters the component accepts]
message: String,
product: Object,
email: {
type: String,
required: true,
default: "none"
validator: function (value) {
[Should return true if value is valid]
}
}
},
data: function() { [Must be a function]
return {
firstName: 'Vue',
lastName: 'Mastery'
}
},
computed: { [Return cached values until]
fullName: function () { [dependencies change]
return this.firstName + ' ' + this.lastName
}
},
watch: { [Called when firstName changes value]
firstName: function (value, oldValue) { ... }
},
methods: { ... },
template: '<span>{{ message }}</span>',
})

Backticks can be used to write multi-line.

Custom Events

Use props (above) to pass data into child components,

custom events to pass data to parent elements.

Set listener on component, within its parent:

<button-counter v-on:incrementBy="incWithVal">

Inside parent component:

methods: {
incWithVal: function (toAdd) { ... }
}

Inside button-counter template:

this.$emit('incrementBy', 5)
[Data sent up to parent]
[Custom event name]

Lifecycle Hooks

Vue js Offers lifecycle hooks. These life cycle hooks are used to execute specific actions on specific moments.

Here are these hooks:

  1. beforeCreate
  2. created
  3. beforeMount
  4. mounted
  5. beforeUpdate
  6. updated
  7. beforeDestroy
  8. destroyed

Here is an example of mounted hook:

new Vue({
methods:{
init(){
//call API
//Setup game
}
},
mounted(){
this.init()
}
})

Image Source: Vue.js Guide

Slots

Vue implements a content distribution API inspired by the Web Components spec draft, using the <slot> element to serve as distribution outlets for content.

Let’s describe it.

Component template:

<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot>Default content</slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>

Use of component with data for slot:

<app-layout>
<h1 slot="header">Page title</h1>
<p>the main content.</p>
<p slot="footer">Contact info</p>
</app-layout>

Also,

It’s very important to understand slots vs. props.

More on slots here.

Lastly, a Few More Vue.js Libraries to Know

Vue CLI

Command line interface for rapid Vue development. This framework is highly recommended for SPA development.

Vue Router
Vue Router is a very useful routing system to create navigation for a Single-Page Application. This library can be used to guard routes and many other features.

VueX Store

Vue Store is used for state management in Vue js app.

Vue DevTools

This is a browser extension for debugging Vue applications.

Nuxt.js

Library for server side rendering, code-splitting, hot-reloading, static generation and more.

The original post can be found here.

--

--

Dhrubok Infotech Services

Supercharge your business with tailor-made software solutions.