Setting Up a Vue.js Project
Using Vue CLI to Create a Project
Method 1: Command Line
Execute the following command in your terminal:
vue create project-name
Method 2: Graphical Interface
Open your terminal and run:
vue ui
This command launches the Vue Project Manager in your browser, allowing you to create and manage projects through a visual interface.
After the project is created, you can run it using:
npm run serve
The Role of Node.js
Node.js is a JavaScript runtime environment that enables server-side execution of JavaScript. Its fundamental to modern frontend development workflows, including those for Vue.js.
Key characteristics of Node.js include:
- Event-driven, non-blocking I/O model for handling concurrent operations efficiently.
- npm (Node Package Manager) for managing JavaScript packages and dependencies.
- Cross-platform compatibility across Windows, macOS, and Linux.
- A vast ecosystem of tools and libraries that support development and build processes.
Node.js provides the foundation for tools like Vue CLI, wich is used to scaffold, develop, and build Vue applications. It also runs the development server and handles tasks such as code transpilation and module bundling.
Core Vue.js Concepts
1. Single-File Components
Vue.js organizes code into Single-File Components (SFCs) with a .vue extension. An SFC encapsulates template, script, and style logic in one file.
<template>
<div class="custom-component">
<h2>{{ title }}</h2>
<button @click="modifyTitle">Update Title</button>
</div>
</template>
<script>
export default {
name: 'CustomComponent',
data() {
return {
title: 'Initial Title'
};
},
methods: {
modifyTitle() {
this.title = 'Updated Title';
}
}
};
</script>
<style scoped>
.custom-component h2 {
color: blue;
}
</style>
2. Text Interpolation
Use double curly braces {{ }} to bind data to the template.
<template>
<div>
<p>Welcome, {{ userName }}!</p>
<p>Score: {{ currentScore }}</p>
</div>
</template>
<script>
export default {
data() {
return {
userName: 'Alex',
currentScore: 10
};
}
};
</script>
3. Attribute Binding
Bind data to HTML attributes using the v-bind directive or its shorthand :.
<template>
<div>
<img :src="imageSource" :alt="imageDescription">
<button :class="{ highlighted: isActive }">Click Me</button>
</div>
</template>
<script>
export default {
data() {
return {
imageSource: '/path/to/image.jpg',
imageDescription: 'A sample image',
isActive: true
};
}
};
</script>
4. Event Handling
Listen to DOM events with the v-on directive or its shorthand @.
<template>
<div>
<button @click="handleClick">Click Event</button>
<input @input="processInput" @keyup.enter="submitForm">
</div>
</template>
<script>
export default {
methods: {
handleClick() {
console.log('Button clicked');
},
processInput(event) {
console.log('Input:', event.target.value);
},
submitForm() {
console.log('Form submitted');
}
}
};
</script>
5. Two-Way Data Binding
Synchronize form input with component state using v-model.
<template>
<div>
<input v-model="userInput" placeholder="Type something...">
<p>You entered: {{ userInput }}</p>
<input v-model.number="numericValue" type="number">
</div>
</template>
<script>
export default {
data() {
return {
userInput: '',
numericValue: 0
};
}
};
</script>
6. Conditional Rendering
Control element visibility with v-if, v-else-if, v-else, and v-show.
<template>
<div>
<p v-if="status === 'loading'">Loading data...</p>
<p v-else-if="status === 'error'">An error occurred.</p>
<p v-else>Data loaded successfully.</p>
<div v-show="isVisible">This element is conditionally shown.</div>
</div>
</template>
<script>
export default {
data() {
return {
status: 'loading',
isVisible: true
};
}
};
</script>
7. Making HTTP Requests with Axios
Axios is a promise-based HTTP client. Install it via npm:
npm install axios
Basic usage in a component:
import axios from 'axios';
export default {
methods: {
fetchUserData() {
axios.get('/api/user/profile')
.then(response => {
console.log('User data:', response.data);
})
.catch(error => {
console.error('Request failed:', error);
});
},
sendFormData() {
axios({
method: 'post',
url: '/api/data/submit',
data: { key: 'value' }
}).then(res => {
// Handle response
});
}
}
};
To resolve cross-origin issues during development, configure a proxy in vue.config.js:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8080',
pathRewrite: { '^/api': '' }
}
}
}
};
Implementing Client-Side Routing with Vue Router
Vue Router enables navigation in single-page applications by mapping URL paths to components.
Basic Configuration
import Vue from 'vue';
import VueRouter from 'vue-router';
import HomePage from './views/HomePage.vue';
Vue.use(VueRouter);
const appRoutes = [
{
path: '/',
name: 'home',
component: HomePage
},
{
path: '/about',
name: 'about',
component: () => import('./views/AboutPage.vue')
},
{
path: '/dashboard',
component: () => import('./views/Dashboard.vue'),
redirect: '/dashboard/overview',
children: [
{
path: 'overview',
component: () => import('./views/dashboard/Overview.vue')
},
{
path: 'settings',
component: () => import('./views/dashboard/Settings.vue')
}
]
},
{
path: '*',
redirect: '/not-found'
}
];
const router = new VueRouter({
routes: appRoutes
});
export default router;
Managing Application State with Vuex
Vuex provides centralized state management for Vue applications.
Store Structure
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
authStatus: 'guest',
userName: 'Visitor'
},
getters: {
formattedUserName: state => `User: ${state.userName}`
},
mutations: {
setUserName(state, newName) {
state.userName = newName;
},
setAuthStatus(state, status) {
state.authStatus = status;
}
},
actions: {
authenticateUser({ commit }) {
return axios.post('/api/auth/login', {
username: 'demo',
password: 'demo123'
}).then(response => {
if (response.data.success) {
commit('setUserName', response.data.user.name);
commit('setAuthStatus', 'authenticated');
}
});
}
}
});
Integrating the Store
In your main application file:
import Vue from 'vue';
import App from './App.vue';
import store from './store';
new Vue({
store,
render: h => h(App)
}).$mount('#app');
Using Store State and Actions in Components
<template>
<div>
<p>Status: {{ $store.state.authStatus }}</p>
<p>Name: {{ $store.state.userName }}</p>
<p>Formatted: {{ $store.getters.formattedUserName }}</p>
<button @click="updateName">Change Name</button>
<button @click="loginUser">Login</button>
</div>
</template>
<script>
export default {
methods: {
updateName() {
this.$store.commit('setUserName', 'New User');
},
loginUser() {
this.$store.dispatch('authenticateUser');
}
}
};
</script>