Vue.js is a popular JavaScript framework for building user interfaces. Here’s a cheat sheet with some essential Vue.js concepts and syntax:
Installation
Include Vue.js in your HTML file or use a package manager like npm or yarn:
<!-- Include from CDN -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<!-- or install via npm/yarn -->
<!-- npm install vue -->
<!-- yarn add vue -->
Vue Instance
var app = new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
}
});
Template Syntax
<div id="app">
<p>{{ message }}</p>
</div>
Directives
v-bind:Bind an attribute or a class dynamically:
<a v-bind:href="url">Link</a>
<div v-bind:class="{ active: isActive }"></div>
v-model:
Two-way data binding for form input:
<input v-model="message">
v-if, v-else-if, v-else:
Conditional rendering:
<p v-if="seen">Now you see me</p>
<p v-else>Now you don't</p>
v-for:
Iterate through an array:
<ul>
<li v-for="item in items">{{ item.text }}</li>
</ul>
Methods
Define methods in the Vue instance:
methods: {
greet: function() {
alert('Hello, Vue!');
}
}
Computed Properties
computed: {
reversedMessage: function() {
return this.message.split('').reverse().join('');
}
}
Watchers
watch: {
message: function(newValue, oldValue) {
console.log('Message changed:', newValue, oldValue);
}
}
Lifecycle Hooks
- beforeCreate, created:
- beforeMount, mounted:
- beforeUpdate, updated:
- beforeDestroy, destroyed:
Components
Vue.component('my-component', {
template: '<div>A custom component</div>'
});
// Register globally
Vue.component('my-component', {
// ...
});
// Register locally
var app = new Vue({
components: {
'my-component': {
template: '<div>A local component</div>'
}
}
});
Event Handling
<button v-on:click="greet">Click me</button>
Filters
<p>{{ message | capitalize }}</p>
Vue.filter('capitalize', function(value) {
if (!value) return '';
value = value.toString();
return value.charAt(0).toUpperCase() + value.slice(1);
});
Routing (Vue Router)
npm install vue-router
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
];
const router = new VueRouter({
routes
});
State Management (Vuex)
npm install vuex
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment: state => state.count++
}
});
This cheat sheet provides an overview of basic Vue.js concepts. For more detailed information and examples, refer to the Vue.js documentation.