Introduction
Vue.js is a popular JavaScript framework for building user interfaces. It is simple, flexible, and beginner-friendly. With Vue, developers can create single-page applications and dynamic web pages with less effort. This cheatsheet will give you a quick guide to important concepts, syntax, and examples so you can use Vue effectively.
1. Vue Instance
Every Vue application starts with creating a Vue instance.
const app = Vue.createApp({
data() {
return {
message: "Hello Vue!"
};
}
});
app.mount('#app');The
datafunction returns an object with variables that can be used in the HTML template.mount('#app')connects Vue with the element havingid="app".
2. Template Syntax
Vue uses double curly braces {{ }} to show data in HTML.
<div id="app">
<p>{{ message }}</p>
</div>Anything inside
{{ }}will be replaced with the value fromdata.
3. Directives
Directives are special attributes in Vue that start with v-.
v-bind
Binds attributes to values.
<img v-bind:src="imageUrl">Shortcut: :src="imageUrl"
v-model
Creates two-way binding between input and data.
<input v-model="message">v-if, v-else, v-else-if
Conditionally shows elements.
<p v-if="isVisible">Visible</p>
<p v-else>Hidden</p>v-for
Loops through lists.
<li v-for="item in items" :key="item.id">{{ item.name }}</li>4. Methods
Define functions inside the Vue instance.
methods: {
greet() {
return "Hello, " + this.message;
}
}thisrefers to the current Vue instance.
5. Computed Properties
Used for values that depend on other data.
computed: {
reversedMessage() {
return this.message.split('').reverse().join('');
}
}Computed properties are cached and only update when dependencies change.
6. Watchers
Run code when data changes.
watch: {
message(newVal, oldVal) {
console.log("Message changed from", oldVal, "to", newVal);
}
}
Join the conversation! Your thoughts help the community grow.