TechLearn Hub

Vue.js: A Beginner's Guide

Learn components, reactivity, directives, APIs and the essential skills for building modern web applications.

Vue.js, commonly called Vue, is a JavaScript framework for building user interfaces. It helps developers create interactive websites and web applications using reusable components and reactive data.

Simple definition: Vue helps you connect application data to a user interface, so the page can update when that data changes.

Vue can be used for small interactive features on an existing website or for complete single-page applications. Basic knowledge of HTML, CSS and JavaScript will make it easier to learn.

1. What Is Vue.js?

Vue is an open-source JavaScript framework designed for building user interfaces. It provides a component system, reactive data handling and tools that help developers organize interactive applications.

Vue can be introduced gradually into a website, or used with its wider ecosystem to build a complete application.

Examples of applications that can use Vue include:

  • Admin dashboards.
  • Online stores.
  • Interactive forms.
  • Personal websites.
  • Product catalogs.
  • Task management applications.
  • Data-driven interfaces.
Vue is a framework, not a programming language. JavaScript is still the main language used in a typical Vue project.

2. Why Do Developers Use Vue?

Vue offers several useful features for frontend development:

  • Reusable components.
  • Reactive data updates.
  • Template syntax that builds on HTML.
  • Event handling and form binding.
  • Support for TypeScript.
  • Tools for routing and shared application state.
  • Integration with APIs and backend services.
  • Options for small websites and larger applications.

Vue is also useful when you want to add interactive functionality to an existing website without rewriting the entire site.

3. Vue and JavaScript

Vue does not replace JavaScript. It adds a framework and conventions that make it easier to build and maintain user interfaces.

In plain JavaScript, you might update an element like this:

document.getElementById("message").textContent = "Hello!";

In Vue, you can connect the displayed text to application data:

<script setup>
const message = "Hello Vue!";
</script>

<template>
  <p>{{ message }}</p>
</template>

Vue renders the message in the template. When you use reactive data, Vue can also update the interface when that data changes.

4. Vue Components

A component is a reusable part of a user interface. Components help you divide a large application into smaller, understandable pieces.

Examples include:

  • Navigation bar.
  • Login form.
  • Product card.
  • Search box.
  • User profile.
  • Notification panel.
  • Page footer.

Vue Single-File Components commonly use the .vue extension. A component can contain its template, JavaScript logic and styles.

<script setup>
const title = "Welcome";
</script>

<template>
  <section>
    <h2>{{ title }}</h2>
    <p>This is a reusable Vue component.</p>
  </section>
</template>

<style scoped>
section {
  padding: 16px;
}
</style>

5. Vue Templates and Data Binding

Vue templates describe the content that should appear on the screen. They look similar to HTML but support additional features such as interpolation, directives and event bindings.

For example:

<script setup>
const username = "Amina";
</script>

<template>
  <h1>Welcome, {{ username }}!</h1>
</template>

The double curly braces display the value of username. This is called text interpolation.

You can also bind an HTML attribute to a value using the colon shorthand for v-bind.

<img :src="imageUrl" alt="Product image">

6. Vue Reactivity and ref()

Reactivity is one of Vue's most important features. When reactive data changes, Vue updates the parts of the interface that depend on it.

The ref() function creates a reactive reference. In JavaScript code, you normally read or change the value through .value.

<script setup>
import { ref } from "vue";

const count = ref(0);

function increase() {
  count.value++;
}
</script>

<template>
  <button @click="increase">
    Count: {{ count }}
  </button>
</template>

Clicking the button calls increase(). The count changes, and Vue updates the displayed value. In a template, Vue automatically unwraps a top-level ref for display.

Using ref() with text

import { ref } from "vue";

const username = ref("John");

username.value = "Amina";

Use ref() when you want a value to be reactive and you may need to replace that value later.

Using reactive()

The reactive() function is another way to make an object reactive.

import { reactive } from "vue";

const user = reactive({
  name: "Amina",
  age: 25
});

user.age = 26;

Both ref() and reactive() are useful. Choose the one that makes the data and your code easiest to understand.

7. Vue Directives

Directives are special Vue attributes that add behavior to elements in a template.

DirectivePurpose
v-ifConditionally renders content.
v-elseProvides an alternative conditional branch.
v-forRenders a list of items.
v-bindConnects an attribute to an expression.
v-modelCreates convenient two-way form binding.
v-showShows or hides an element using CSS display behavior.
v-onListens for events.

v-if

Use v-if when content should only be rendered if a condition is true.

<script setup>
import { ref } from "vue";

const loggedIn = ref(true);
</script>

<template>
  <p v-if="loggedIn">Welcome back!</p>
  <p v-else>Please sign in.</p>
</template>

v-for

Use v-for to display a list. When rendering a list, provide a stable key where possible.

<script setup>
const users = [
  { id: 1, name: "Amina" },
  { id: 2, name: "John" },
  { id: 3, name: "Mary" }
];
</script>

<template>
  <ul>
    <li v-for="user in users" :key="user.id">
      {{ user.name }}
    </li>
  </ul>
</template>

v-bind

The long syntax is v-bind:src. The shorter syntax is :src.

<img :src="imageUrl" alt="Example image">

v-show

Use v-show when an element should remain in the DOM but be shown or hidden using CSS display behavior.

<p v-show="isVisible">This message can be hidden.</p>

Unlike v-if, v-show does not normally remove the element from the DOM when the condition is false.

8. Events, Methods and Forms

Handling click events

Vue can listen for browser events using v-on or the shorter @ syntax.

<script setup>
function sayHello() {
  alert("Hello Vue!");
}
</script>

<template>
  <button @click="sayHello">
    Say Hello
  </button>
</template>

Using v-model with forms

The v-model directive connects a form input to application data.

<script setup>
import { ref } from "vue";

const username = ref("");
</script>

<template>
  <label for="username">Your name</label>

  <input
    id="username"
    v-model="username"
    placeholder="Enter your name"
  >

  <p>Hello, {{ username }}!</p>
</template>

As the user types, the reactive value updates and the displayed greeting changes.

9. Computed Properties and Watchers

Computed properties

A computed property creates a value from other reactive data. Vue tracks its dependencies and caches the result until those dependencies change.

<script setup>
import { ref, computed } from "vue";

const firstName = ref("Amina");
const lastName = ref("Abdullahi");

const fullName = computed(() =>
  firstName.value + " " + lastName.value
);
</script>

<template>
  <p>Full name: {{ fullName }}</p>
</template>

Watchers

The watch() function runs a callback when a watched source changes. It is useful for side effects such as requesting data or synchronizing something outside the component.

import { ref, watch } from "vue";

const searchText = ref("");

watch(searchText, (newValue) => {
  console.log("Search changed:", newValue);
});
Use computed properties for values derived from other data. Use watchers when a change should trigger an action or side effect.

10. Props and Emits

Props

Props allow a parent component to pass data to a child component.

For example, a parent template might use:

<UserProfile name="Amina" />

The child component can declare the prop:

<script setup>
defineProps({
  name: String
});
</script>

<template>
  <p>User: {{ name }}</p>
</template>

Props are intended to be passed from parent to child. A child component should not directly mutate a prop as if it owned that value.

Emits

A child component can notify its parent by emitting an event.

<script setup>
const emit = defineEmits(["save"]);

function saveData() {
  emit("save");
}
</script>

<template>
  <button @click="saveData">Save</button>
</template>

The parent can listen for the event using a listener such as @save.

11. Composition API and Options API

Composition API

The Composition API lets you organize component logic using imported Vue functions. Many modern Vue components use the Composition API with <script setup>.

Common functions include:

  • ref() for reactive references.
  • reactive() for reactive objects.
  • computed() for derived values.
  • watch() for responding to changes.
  • onMounted() for component lifecycle work.

Options API

The Options API organizes component logic into options such as data, methods, computed, watch and lifecycle hooks.

<script>
export default {
  data() {
    return {
      count: 0
    };
  },
  methods: {
    increase() {
      this.count++;
    }
  }
};
</script>

<template>
  <button @click="increase">
    Count: {{ count }}
  </button>
</template>

Both APIs are supported. Beginners can learn either approach; the best choice often depends on the project and the codebase they are working with.

12. Vue Lifecycle Hooks

Components go through different stages, including being created, mounted, updated and unmounted. Lifecycle hooks let you run code at specific stages.

<script setup>
import { onMounted, onUnmounted } from "vue";

onMounted(() => {
  console.log("Component mounted");
});

onUnmounted(() => {
  console.log("Component unmounted");
});
</script>

Lifecycle hooks can be useful for setting up event listeners, starting timers, initializing integrations and cleaning up resources.

13. Vue Router

Vue Router is the official routing solution commonly used to navigate between views in Vue applications.

A website might have routes such as:

  • Home.
  • About.
  • Products.
  • Profile.
  • Settings.

In a single-page application, Vue Router can change the displayed view without requiring a full document reload for every navigation.

For applications that need multiple routes, start with the official Vue Router documentation and follow its installation and configuration instructions.

14. Pinia and State Management

Pinia is a state management library commonly used with Vue. It is useful when several components need access to the same application data.

Shared state might include:

  • Shopping cart contents.
  • Logged-in user information.
  • Application preferences.
  • Notifications.
  • Selected language or theme.

Not every project needs a state management library. Small applications can often manage state inside their components, while larger applications may benefit from shared stores.

15. Working with APIs

Vue applications commonly request information from backend APIs. JavaScript's fetch() function can make an HTTP request.

<script setup>
import { ref, onMounted } from "vue";

const users = ref([]);
const loading = ref(true);
const error = ref("");

onMounted(async () => {
  try {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/users"
    );

    if (!response.ok) {
      throw new Error("Could not load users.");
    }

    users.value = await response.json();
  } catch (err) {
    error.value = "Unable to load data. Please try again.";
  } finally {
    loading.value = false;
  }
});
</script>

<template>
  <p v-if="loading">Loading users...</p>

  <p v-else-if="error">{{ error }}</p>

  <ul v-else>
    <li v-for="user in users" :key="user.id">
      {{ user.name }}
    </li>
  </ul>
</template>

This example demonstrates loading, success and error states. The example API is for practice; production applications should use an appropriate API and handle authentication, permissions and errors correctly.

What is JSON?

JSON is a common format for exchanging data between applications and APIs.

{
  "name": "Amina",
  "age": 25,
  "country": "Nigeria"
}

A Vue application can store API responses in reactive variables and display the returned information.

16. Vue and TypeScript

Vue supports TypeScript, which adds static type checking to JavaScript development. TypeScript can make larger projects easier to maintain and help developers catch some errors during development.

A Vue component using TypeScript can look like this:

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

const age = ref<number>(25);
const username = ref<string>("Amina");

function updateAge(value: number) {
  age.value = value;
}
</script>

<template>
  <p>{{ username }} is {{ age }} years old.</p>
</template>

The lang="ts" attribute tells the tooling that the script uses TypeScript. A TypeScript project should also run its configured type-checking process.

17. Vue and Vite

Vite is a frontend development tool commonly used to create and build Vue applications. It provides a development server and a production build workflow.

To create a Vue project, you can use the official Vue project creation command:

npm create vue@latest

Follow the prompts to select the features you want. Then enter the project directory and install dependencies:

cd my-vue-project
npm install
npm run dev

When you are ready to prepare the project for deployment, run the build command configured in the project:

npm run build
Vite is the development and build tool; Vue is the framework used to create the user interface. They work together but serve different purposes.

18. Basic Vue Project Structure

A Vue project might contain files and folders like these:

my-vue-project/
├── public/
├── src/
│   ├── assets/
│   ├── components/
│   ├── App.vue
│   └── main.js
├── index.html
├── package.json
├── package-lock.json
└── vite.config.js
  • src/ contains the application source code.
  • components/ can hold reusable Vue components.
  • App.vue is commonly the root component.
  • main.js is commonly the application entry point.
  • public/ contains static files served as-is.
  • package.json lists scripts and dependencies.
  • vite.config.js can hold Vite configuration.

The exact structure depends on the selected template and the options chosen during project creation.

19. Vue vs React

FeatureVueReact
CategoryJavaScript frameworkJavaScript library for user interfaces
ComponentsYesYes
TemplatesHTML-based template syntaxCommonly JSX or JavaScript-based UI descriptions
ReactivityBuilt-in reactive systemState and rendering mechanisms provided by React
RoutingVue Router is commonly usedOften uses a separate routing library
State managementLocal state or tools such as PiniaLocal state or a variety of external solutions

Both Vue and React can build modern interactive applications. Choose based on your project, preferences and the ecosystem you want to learn.

Vue vs Angular

FeatureVueAngular
ApproachProgressive JavaScript frameworkComprehensive web application framework
LanguageJavaScript or TypeScriptTypeScript is commonly used
ComponentsYesYes
RoutingVue RouterAngular Router
LearningOften approachable for beginnersIncludes a broader set of framework concepts

Neither framework is automatically best for every situation. Consider the project's needs and the team's experience.

20. Vue, Backend Systems and Security

Vue is primarily a frontend framework. A full application may also need a backend server, authentication, a database and APIs.

A common architecture looks like this:

Vue Frontend
     |
     v
   Backend API
     |
     v
  Database Server

The backend is responsible for handling trusted operations and communicating with the database. The frontend should not contain confidential database credentials.

Important security practices include:

  • Use HTTPS on production websites.
  • Validate important input on the server.
  • Enforce authentication and permissions on the backend.
  • Keep private API keys and credentials out of browser code.
  • Handle failed API requests safely.
  • Keep project dependencies updated.
  • Use Vue's normal text interpolation for untrusted text rather than inserting arbitrary HTML.
Never assume that hiding a button in the Vue interface is enough to protect an operation. The backend must check whether the user is authorized to perform it.

21. Responsive Vue Applications

Vue can build interfaces for phones, tablets and desktop computers. Responsive layouts are mainly created with HTML and CSS, while Vue handles application behavior and reactive content.

Useful responsive design techniques include:

  • CSS Flexbox.
  • CSS Grid.
  • Media queries.
  • Flexible widths and spacing.
  • Responsive images.
  • Accessible buttons and form controls.

Always test your interface at different screen sizes, especially if many visitors use mobile devices.

22. Vue for Mobile Applications

Vue is mainly a web framework. Vue-based technologies can also be used as part of a larger workflow for hybrid or mobile applications.

However, Vue itself is not a native Android or iOS framework. If you want to publish a mobile app, check the capabilities and limitations of the mobile framework you choose.

23. Beginner Vue Project Ideas

Build small applications to practise your skills:

  • Counter application.
  • To-do list.
  • Calculator.
  • Notes application.
  • Weather interface.
  • Expense tracker.
  • Quiz application.
  • Product catalog.
  • Movie search interface.
  • Simple dashboard.

Start with local sample data. Once you understand components and reactivity, connect your project to a suitable API.

Example: A simple Vue counter

<script setup>
import { ref } from "vue";

const count = ref(0);

function increase() {
  count.value++;
}

function decrease() {
  count.value--;
}
</script>

<template>
  <h1>Counter</h1>
  <p>Count: {{ count }}</p>

  <button @click="increase">Increase</button>
  <button @click="decrease">Decrease</button>
</template>

This example demonstrates reactive data and event handling. It can be the starting point for a more advanced counter with reset and minimum-value features.

24. Common Vue Beginner Mistakes

  • Trying to learn Vue without understanding basic JavaScript.
  • Putting too much unrelated logic into one component.
  • Forgetting stable keys when rendering lists.
  • Mutating props directly instead of communicating through events.
  • Not handling loading and error states for API requests.
  • Exposing private keys in frontend code.
  • Assuming all data is trustworthy because it appears in the UI.
  • Making components more complicated than necessary.

25. Vue Learning Roadmap

  1. Learn HTML and semantic elements.
  2. Learn CSS and responsive layouts.
  3. Understand JavaScript variables, functions and arrays.
  4. Learn objects, modules and asynchronous JavaScript.
  5. Create a Vue project.
  6. Learn components and templates.
  7. Understand reactivity and ref().
  8. Practise directives, events and forms.
  9. Learn computed properties and watchers.
  10. Understand props and emits.
  11. Explore Composition API and lifecycle hooks.
  12. Learn Vue Router.
  13. Explore Pinia when you need shared state.
  14. Practise working with APIs.
  15. Learn TypeScript if your project needs it.
  16. Build and deploy a complete project.

26. Vue Cheat Sheet

FeaturePurpose
ref()Create a reactive reference.
reactive()Create a reactive object.
computed()Calculate a value from reactive dependencies.
watch()Run a callback when a watched source changes.
v-ifConditionally render content.
v-forRender a list of items.
v-modelConnect form input and application state.
@clickListen for a click event.
:srcBind an element attribute.
defineProps()Declare props for a component.
defineEmits()Declare component events.
onMounted()Run code after a component mounts.

27. Frequently Asked Questions

Is Vue a programming language?

No. Vue is a JavaScript framework for building user interfaces.

Do I need JavaScript before learning Vue?

Yes. Basic JavaScript knowledge will make Vue easier to understand.

Can Vue build websites?

Yes. Vue can be used for interactive websites and complete web applications.

Can Vue work with APIs?

Yes. Vue applications can request and display information from backend APIs.

Can I use TypeScript with Vue?

Yes. Vue supports TypeScript, and TypeScript can be useful for maintaining larger projects.

What file extension do Vue components use?

Vue Single-File Components commonly use the .vue extension.

Is Vue suitable for beginners?

Vue can be approachable for beginners, especially those who already understand HTML, CSS and JavaScript.

Can Vue build large applications?

Yes. Vue and its ecosystem provide tools that can support large applications when they are designed and maintained carefully.

What is the difference between Vue and Vite?

Vue is the framework for building the interface. Vite is a development and build tool often used to run and build Vue projects.

Does Vue include routing?

Vue Router is the official routing solution commonly used for navigation in Vue applications. It is installed and configured as needed.

What is Pinia?

Pinia is a state management library used to share application state across Vue components.

Conclusion

Vue.js is a flexible JavaScript framework for building interactive user interfaces and web applications. Its component system, reactivity, directives, event handling and wider ecosystem make it a useful choice for frontend development.

If you are a beginner, start with JavaScript fundamentals, components, reactive data, forms and events. Then move on to APIs, routing, shared state, TypeScript and complete projects.

Your next step: Create a small Vue application with a counter or to-do list. Practise changing reactive data and splitting your interface into reusable components.

↑ Back to top