Vue Introduction
Vue is a progressive JavaScript framework for building user interfaces.
What is Vue?
- Vue is a JavaScript framework for the part of a website users see and use
- It was created by Evan You and first released in 2014
- The current major version is Vue 3
- Vue is progressive: you can add it to one part of a page, or build a full app with it
Vue takes care of keeping the page in sync with your data. You change a variable, and Vue updates every place on the page that uses it. This is called reactivity.
Why Learn Vue?
| Reason | What it means for you |
|---|---|
| Easy to start | Templates look like normal HTML |
| Clear structure | HTML, JavaScript and CSS of a component sit in one file |
| Fast and small | Vue apps load quickly, even on slow mobile internet |
| Good tools | Vite, Vue Router, Pinia and Vue DevTools work well together |
| Jobs and freelancing | Many dashboards and admin panels are built with Vue |
Single-File Components
A Vue app is built from components. Each component usually lives in a .vue file with up to three parts:
Example
<script setup>
const shopName = "Saddar Mobile Centre";
const city = "Karachi";
</script>
<template>
<div class="shop">
<h2>{{ shopName }}</h2>
<p>Located in {{ city }}</p>
</div>
</template>
<style scoped>
.shop {
border: 1px solid #42b883;
padding: 12px;
}
</style>Saddar Mobile Centre Located in Karachi
| Part | Job |
|---|---|
<script setup> | The component's JavaScript: data and functions |
<template> | The HTML that appears on the page |
<style scoped> | CSS that applies only to this component |
Reactivity in One Example
Example
<script setup>
import { ref } from "vue";
const stock = ref(5);
function sellOne() {
stock.value--;
}
</script>
<template>
<p>Notebooks left: {{ stock }}</p>
<button @click="sellOne">Sell one</button>
</template>Notebooks left: 5 (after 2 clicks) Notebooks left: 3
You never touch the page directly. You only change stock, and Vue does the rest.
Composition API and Options API
Vue has two ways to write components:
- Options API: an older style with
data(),methodsandcomputedsections in an object - Composition API: functions like
ref()andcomputed()inside<script setup>
Both are supported in Vue 3. This tutorial uses the Composition API, which is recommended for new projects and works very well with TypeScript.
If you find old tutorials using new Vue({ ... }), that is Vue 2. Vue 2 reached its end of life at the end of 2023, so learn Vue 3.
What You Should Know First
- HTML and CSS basics
- JavaScript variables, functions, arrays and objects
- Arrow functions and
import/export
Exercise
Exercise
What does "reactivity" mean in Vue?
