Vue.js is a progressive framework for building user interfaces. Its design allows for gradual integration and provides a reactive architecture that facilitates the development of SPA applications.
Installation and Setup of Vue.js
Installation via CDN
For simple projects, you can add Vue.js directly from a CDN.
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
Installation with NPM
npm install vue
CLI
Global Installation:
Vue CLI allows for setting up advanced projects
npm install -g vue-cli
Create a Project with Vue CLI
To create a new Vue.js project:
vue create project-name
Check Vue CLI Version
Verify that Vue CLI is installed correctly.
vue --version
Structure of a Vue Project
Typical Folder Structure
project-name/
├── node_modules/
├── public/
│ └── index.html
├── src/
│ ├── assets/
│ ├── components/
│ ├── App.vue
│ └── main.js
├── package.json
└── vue.config.js
src/
Main folder containing the source code.
components/
Where Vue components are located.
App.vue
Root component of the application.
main.js
Entry point of the application.
Components
Basic Vue Component
Components are reusable instances of Vue. A Vue component consists of three main parts: <template>
, <script>
, and <style>
.
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: "Hello World"
}
}
}
</script>
<style scoped>
div {
color: blue;
}
</style>
Using Components in Templates
To use a component in the template:
<my-component></my-component>
Defining a Component using Class Style
import Vue from 'vue';
import Component from 'vue-class-component';
@Component
export default class MyComponent extends Vue {
message = 'Hello from a class component!';
}
Data Interpolation
Allows rendering variables in the DOM with the syntax {{}}
.
<p>{{ message }}</p>
Props
Data can be passed from a parent component to a child using props.
// Child component
export default {
props: ['message']
}
In the parent component:
<child :message="parentMessage"></child>
Emitting Events
To communicate from the child to the parent, events are emitted.
// Child component
this.$emit('customEvent', data)
In the parent component:
<child @customEvent="handleEvent"></child>
Slot
Allows the parent component to inject content into the child.
<template>
<div>
<slot></slot>
</div>
</template>
And in the parent:
<child>This is the slot content</child>
Directives
Conditional Directives
v-if
Renders an element only if the expression is true.
<p v-if="show">This text is shown if show is true</p>
v-else
Adds an alternative condition to v-if
.
<p v-if="show">Show</p>
<p v-else>Do not show</p>
v-show
Similar to v-if
, but instead of removing the node from the DOM, it controls visibility with CSS (display
).
<p v-show="show">This text is visible according to show</p>
Iteration Directives
v-for
Iterates over a list of data, creating an element for each item.
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
Event Directives
v-on
Listens for DOM events. v-on
can be shortened as @
.
<button v-on:click="alert">Click</button>
<!-- Or with shorthand syntax -->
<button @click="alert">Click</button>
Binding Directives
v-bind
Binds DOM attributes or properties to Vue properties. Its abbreviation is :
.
<img v-bind:src="imageURL" />
<!-- Or with shorthand syntax -->
<img :src="imageURL" />
v-model
Creates a two-way binding between a form field and the Vue state.
<input v-model="name" />
<p>The name is: {{ name }}</p>
Component Lifecycle
Vue has a series of hooks or events that allow code execution at key moments in the component lifecycle.
mounted
Executed when the component has been mounted in the DOM.
export default {
mounted() {
console.log("The component has been mounted");
}
}
created
Triggered when the component instance has been created, but not yet mounted in the DOM.
export default {
created() {
console.log("Instance created");
}
}
beforeDestroy
Executed just before the component is destroyed and removed from the DOM.
export default {
beforeDestroy() {
console.log("Component about to be destroyed");
}
}
Reactivity
Data
The data
property in Vue stores the reactive state of the component.
data() {
return {
message: "Hello",
counter: 0
}
}
Computed Properties
These are properties that depend on others and update automatically when the dependencies change.
computed: {
reversedMessage() {
return this.message.split('').reverse().join('');
}
}
Watchers
Watch for changes in properties and execute code in response.
watch: {
counter(newValue, oldValue) {
console.log(`Counter changed from ${oldValue} to ${newValue}`);
}
}
Style Management
Scoped Styles
The scoped
attribute makes the defined styles only affect the current component.
<style scoped>
h1 {
color: red;
}
</style>
Dynamic Classes
You can apply classes conditionally or dynamically using v-bind:class
.
<div :class="{ active: isActive }">Content</div>
Dynamic Inline Styles
Use v-bind:style
to apply inline styles reactively.
<div :style="{ color: textColor, fontSize: fontSize + 'px' }">Text</div>
Transitions and Animations
Basic Transitions
Vue.js provides support for transitions on elements added or removed from the DOM:
<transition name="fade">
<p v-if="visible">Hello, world!</p>
</transition>
CSS for Transitions
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
Routing with Vue Router
Installing Vue Router
Install the Vue Router package.
npm install vue-router
Basic Setup
Set up the routes and router in your Vue application.
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from './components/Home.vue'
import About from './components/About.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = new VueRouter({
routes
})
new Vue({
router,
render: h => h(App)
}).$mount('#app')
Linking to Routes
Use router-link
to navigate between pages.
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
Accessing Route Parameters
To access dynamic parameters in routes:
const routes = [
{ path: '/user/:id', component: User }
]
In the component:
export default {
mounted() {
console.log(this.$route.params.id);
}
}
Vuex for State Management
Installing Vuex
npm install vuex
Setting Up a Store
Define a store with state
, mutations
, actions
, and getters
.
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
counter: 0
},
mutations: {
increment(state) {
state.counter++
}
},
actions: {
increment({ commit }) {
commit('increment')
}
},
getters: {
counter: state => state.counter
}
})
export default store
Accessing the Store in Components
You can access the store from any component:
this.$store.state.counter
this.$store.commit('increment')
this.$store.dispatch('increment')
Vue API
Vue Instance
The main Vue instance can be created as follows:
new Vue({
el: '#app',
data: {
message: 'Hello from Vue!'
}
});
Configure Vue Behavior
Vue.config.productionTip = false;
Build and Deployment Configuration
Compile for Production
Use Vue CLI to compile the project optimized for production.
npm run build
Local Server
To run a local server on port 8080 (by default).
npm run serve