Youssef Samir

Get in touch

Vue.js

A quick guide to Vue.js syntax, directives, and components to help you build interactive and reactive user interfaces.

Getting Started

Vue CDN

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

Include this script tag in your HTML to use Vue.js via CDN.

Install Vue CLI

npm install -g @vue/cli

Install Vue CLI globally on your machine to create and manage Vue.js projects.

Create a Vue Project

vue create <project-name>

Create a new Vue project with the specified name.

Run Vue Project

npm run serve

Start a local development server to serve your Vue project.

Install Dependencies

npm install

Install all dependencies listed in the package.json file to generate the node_modules folder.

Vue Directives

v-model

<input v-model="message" />

Creates a two-way binding on form input elements.

v-if, v-else-if, v-else

<div v-if="conditionA">A</div>
<div v-else-if="conditionB">B</div>
<div v-else>C</div>

Conditionally render elements based on the value of an expression.

v-show

<div v-show="isVisible">Hello</div>

Toggle the visibility of an element based on an expression.

v-cloak

<div v-cloak>{{ message }}</div>

Keep the element hidden until Vue's compilation is done.

v-on:event or @event

<button v-on:click="doSomething">Click me</button>
<button @click="doSomething">Click me</button>

Listen to DOM events and execute methods.

v-bind

<img v-bind:src="imageSrc" />
<img :src="imageSrc" />

Bind attribute values to expressions.

v-for

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

Render a list of items using a loop.

v-slot

<template v-slot:header>
  <h1>Header Content</h1>
</template>

Define slots for template content insertion in child components.

Events and Methods

Click Event

<button @click="handleClick">Click me</button>

Handle click events.

Key Events (keyup, keydown)

<input @keyup.enter="submitForm" />

Handle keyboard events like keyup and keydown.

Submit Event

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

Handle form submission events.

Mouse Events (mouseover, mouseleave, dblclick, mousemove)

<div @mouseover="handleMouseOver" @mouseleave="handleMouseLeave">...</div>
<div @dblclick="handleDoubleClick">...</div>
<div @mousemove="handleMouseMove">...</div>

Handle various mouse events.

Custom Components

Component Props

<child-component :prop-name="parentData"></child-component>

Pass data to child components via props.

Component Computed

computed: {
  reversedMessage() {
    return this.message.split('').reverse().join('');
  }
}

Define computed properties in components.

Pass Data from Parent to Child

<child-component :prop-name="parentData"></child-component>

Use props to pass data from parent to child.

Pass Data from Child to Parent

this.$emit('customEvent', data)

Emit events to send data from child to parent.

A Component Contains

export default {
  template: '<div>{{ message }}</div>',
  data() {
    return { message: 'Hello' };
  },
  props: ['propName'],
  computed: {
    reversedMessage() {
      return this.message.split('').reverse().join('');
    }
  },
  methods: {
    handleClick() {
      alert('Clicked!');
    }
  },
  components: {
    ChildComponent
  }
}

Define template, data, props, computed, methods, and components.

Vue Project Structure

node_modules

Contains all libraries and dependencies.

public

Contains static assets.

index.html

Main HTML file.

src

Main source directory.

assets

Static assets like images and CSS.

components

Contains Vue components.

App.vue

Root Vue component.

main.js

Entry file for the Vue app.

package.json

Contains dependencies and scripts.

Template Refs

<input ref="inputRef" />

Access DOM elements directly.

Style Scoped

<style scoped>
/* CSS rules */
</style>

Apply styles scoped to the current component only.

Emitting Custom Events

this.$emit('customEvent', data)

Send data from a child to a parent component via events.

Click Event Modifiers

<button @click.stop="handleClick">Click me</button>

Use event modifiers like .stop, .prevent.

Slots

<slot></slot>

Pass templates to components.

Custom Named Slots

<template v-slot:header>
  <h1>Header</h1>
</template>

Define named slots for specific template sections.

Teleport Components

<teleport to="#destination">
  <p>Teleported content</p>
</teleport>

Move content to a different part of the DOM.

Lifecycle Hooks

mounted

mounted() {
  console.log('Component mounted.');
}

Called after the component is inserted into the DOM.

updated

updated() {
  console.log('Component updated.');
}

Called after the component's DOM is updated.

unmounted

unmounted() {
  console.log('Component unmounted.');
}

Called after the component is removed from the DOM.

Two-Way Data Binding

Using v-model for two-way data binding.

Vue Router

Handle routing in a Vue app.

<router-link to="/about">About</router-link>

Define navigation links.

<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

Create dynamic links.

Programmatic Navigation

this.$router.push('/home')

Navigate programmatically in your app.

Fetching Data from an API

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => this.items = data);

Fetch data from an API.

Options API vs Composition API

Learn the differences between these two API styles.

Template Refs in the Options API

mounted() {
  console.log(this.$refs.inputRef);
}

Access template refs in the Options API.

Template Refs in the Composition API

import { ref, onMounted } from 'vue';
const inputRef = ref(null);
onMounted(() => {
  console.log(inputRef.value);
});

Access template refs in the Composition API.

Using Refs for Reactive Values

const count = ref(0);

Create reactive values with ref.

Using Reactive for Reactive Values

const state = reactive({ count: 0 });

Use reactive to create a reactive object.

Computed Values

const doubled = computed(() => count.value * 2);

Define computed values in the Composition API.

Watch vs WatchEffect

watch(() => count.value, (newVal, oldVal) => {
  console.log(newVal);
});

watchEffect(() => {
  console.log(count.value);
});

Watch specific data or dependencies.

Props in the Composition API

const props = defineProps(['propName']);

Define props in the Composition API.

Lifecycle Hooks in the Composition API

import { onMounted, onUpdated, onUnmounted } from 'vue';
onMounted(() => { console.log('Mounted'); });
onUpdated(() => { console.log('Updated'); });
onUnmounted(() => { console.log('Unmounted'); });

Use lifecycle hooks inside the setup method.