Vue Directives Overview Vue directives are special attributes with the v- prefix that allow you to apply reactive behavior to DOM elements. These directives provide powerful capabilities for data binding, conditional rendering, and event handling.
v-for Directive The v-for directive is used for list rendering, allowing you to iterate over arrays or objects. It creates a template for each element in the source data.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue v-for Example</title>
</head>
<body>
<div id="app">
<ul>
<li v-for="(product, index) in products" :key="product.id">
{{ index + 1 }}. {{ product.name }} - ${{ product.price }}
</li>
</ul>
</div>
<script type="module">
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
createApp({
data() {
return {
products: [
{ id: 1, name: 'Laptop', price: 999 },
{ id: 2, name: 'Smartphone', price: 699 },
{ id: 3, name: 'Tablet', price: 399 }
]
}
}
}).mount('#app');
</script>
</body>
</html>
v-bind Directive The v-bind directive dynamically binds one or more attributes to an expression. It's commonly used for class and style bindings, but can be used for any attribute.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue v-bind Example</title>
</head>
<body>
<div id="app">
<img :src="imageUrl" :alt="imageDescription" :class="imageClass">
<p :style="{ color: textColor, fontSize: fontSize + 'px' }">Dynamic styling example</p>
</div>
<script type="module">
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
createApp({
data() {
return {
imageUrl: 'https://picsum.photos/200/200',
imageDescription: 'Random image',
imageClass: 'rounded-image',
textColor: 'blue',
fontSize: 16
}
}
}).mount('#app');
</script>
</body>
</html>
v-if and v-show Directives These directives control element visibility. v-if conditionally renders elements based on truthy/falsy values, while v-show togglles display CSS property.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue Conditional Rendering</title>
</head>
<body>
<div id="app">
<div v-if="isLoggedIn">
<h2>Welcome back, {{ userName }}!</h2>
</div>
<div v-else>
<h2>Please log in to continue</h2>
</div>
<button @click="toggleVisibility">Toggle visibility</button>
<p v-show="isVisible">This paragraph can be shown/hidden</p>
</div>
<script type="module">
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
createApp({
data() {
return {
isLoggedIn: true,
userName: 'John Doe',
isVisible: true
}
},
methods: {
toggleVisibility() {
this.isVisible = !this.isVisible;
}
}
}).mount('#app');
</script>
</body>
</html>
v-on Directive The v-on directive attaches event listeners to elements. It can be used with any DOM event and supports modifiers for common scenarios.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue Event Handling</title>
</head>
<body>
<div id="app">
<button @click="increment">Count: {{ count }}</button>
<button @click="reset">Reset</button>
<p @mouseover="showTooltip">Hover over me for a tooltip</p>
</div>
<script type="module">
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
createApp({
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++;
},
reset() {
this.count = 0;
},
showTooltip() {
alert('You hovered over the paragraph!');
}
}
}).mount('#app');
</script>
</body>
</html>
v-model Directive The v-model directive creates two-way data bindings on form input, textarea, and select elements. It automatically picks the correct way to update the element based on the input type.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue v-model Example</title>
</head>
<body>
<div id="app">
<input type="text" v-model="searchQuery" placeholder="Search...">
<p>You searched for: {{ searchQuery }}</p>
<select v-model="selectedCategory">
<option value="">All categories</option>
<option value="electronics">Electronics</option>
<option value="clothing">Clothing</option>
<option value="books">Books</option>
</select>
<p>Selected category: {{ selectedCategory }}</p>
</div>
<script type="module">
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
createApp({
data() {
return {
searchQuery: '',
selectedCategory: ''
}
}
}).mount('#app');
</script>
</body>
</html>
Vue Component Lifecycle Vue components go through a series of lifecycle hooks during their creation and destruction. These hooks allow you to execute code at specific stages of a component's lifecycle.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue Lifecycle Example</title>
</head>
<body>
<div id="app">
<h1>Lifecycle Demo</h1>
<p>Check console for lifecycle hook messages</p>
</div>
<script type="module">
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
createApp({
data() {
return {
message: 'Component initialized'
}
},
beforeCreate() {
console.log('beforeCreate: Component instance is being created');
},
created() {
console.log('created: Component instance created, data and methods available');
},
beforeMount() {
console.log('beforeMount: Template compiled, not yet mounted to DOM');
},
mounted() {
console.log('mounted: Component mounted to DOM');
this.fetchData();
},
beforeUpdate() {
console.log('beforeUpdate: Data changed, DOM not yet updated');
},
updated() {
console.log('updated: DOM updated with new data');
},
beforeUnmount() {
console.log('beforeUnmount: Component about to be unmounted');
},
unmounted() {
console.log('unmounted: Component completely removed');
},
methods: {
fetchData() {
console.log('Fetching data...');
}
}
}).mount('#app');
</script>
</body>
</html>
Integrating Axios with Vue Axios is a promise-based HTTP client that works well with Vue for making API requests. It simplifies handling HTTP requests and responses.
Basic Axios Usage
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue with Axios</title>
</head>
<body>
<div id="app">
<h2>Product List</h2>
<ul v-if="products.length">
<li v-for="product in products" :key="product.id">
{{ product.name }} - ${{ product.price }}
</li>
</ul>
<p v-else>Loading products...</p>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="module">
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
createApp({
data() {
return {
products: []
}
},
mounted() {
this.loadProducts();
},
methods: {
async loadProducts() {
try {
const response = await axios.get('https://api.example.com/products');
this.products = response.data;
} catch (error) {
console.error('Error loading products:', error);
}
}
}
}).mount('#app');
</script>
</body>
</html>
Axios Request Methods
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Axios Request Methods</title>
</head>
<body>
<div id="app">
<h2>Axios Request Methods Demo</h2>
<button @click="fetchData">GET Request</button>
<button @click="createData">POST Request</button>
<button @click="updateData">PUT Request</button>
<button @click="deleteData">DELETE Request</button>
<div v-if="response">
<h3>Response:</h3>
{{ response }}
</div>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="module">
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';
createApp({
data() {
return {
response: null
}
},
methods: {
async fetchData() {
try {
const result = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
this.response = result.data;
} catch (error) {
this.response = { error: error.message };
}
},
async createData() {
try {
const result = await axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'New Post',
body: 'This is a new post',
userId: 1
});
this.response = result.data;
} catch (error) {
this.response = { error: error.message };
}
},
async updateData() {
try {
const result = await axios.put('https://jsonplaceholder.typicode.com/posts/1', {
id: 1,
title: 'Updated Post',
body: 'This post has been updated',
userId: 1
});
this.response = result.data;
} catch (error) {
this.response = { error: error.message };
}
},
async deleteData() {
try {
const result = await axios.delete('https://jsonplaceholder.typicode.com/posts/1');
this.response = { status: 'Deleted successfully' };
} catch (error) {
this.response = { error: error.message };
}
}
}
}).mount('#app');
</script>
</body>
</html>