Vue.js Cheatsheet
The Vue.js cheatsheet serves as a handy tool for developers, catering to both beginners and seasoned users of the framework. It offers a compact overview of key concepts, syntax, and commands essential for working with Vue.js.
Benefits of Vue.js Cheatsheet
· Ease of Learning
· Flexibility
· Reactive Data Binding
· Component-Based Architecture
· Strong Community and Ecosystem
Purpose of a Vue.js Cheatsheet
· Learning Aid
· Productivity Booster
· Best Practices
Vue.js CheatSheet Includes
Installation and Setup
- Install Node.js and npm
· Make sure you have Node.js and npm (Node Package Manager) installed.
node -v
npm -v
2. Install Vue CLI Once you have Node.js and npm installed, you can install Vue CLI globally using npm:
npm install -g @vue/cli
3. Create a New Vue Project
· Navigate to the directory where you want to create your new project and run
vue create my-vue-app
· Replace my-vue-app with your desired project name
4. Navigate to Your Project Directory
cd my-vue-app
5. Run Your Vue Application
· To start the development server and see your Vue application in action:
npm run serve
Basic File Component
Vue.js components are reusable Vue instances with a name, and we can use them as custom elements. The basic structure of a Vue.js component includes a template, a script, and, optionally, a style section.
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
msg: 'HelloWorld',
props: {
msg: String
}
}
</script>
<style scoped>
h1 {
color: #42b983;
}
</style>
Binding
Binding in Vue.js lets you keep your data in sync with your DOM. The `v-bind` directive is used to dynamically bind one or more additional attributes or a component prop to an expression.
<template>
<div>
<img v-bind:src="imageSrc" />
</div>
</template>
<script>
export default {
data() {
return {
imageSrc: 'https://vuejs.org/images/logo.png'
}
}
}
</script>
Directives
Directives are special tokens in the markup that tell the library to do something to a DOM element. Vue provides several built-in directives such as `v-if`, `v-for`, and `v-show`.
<template>
<div v-if="isVisible">
This text is conditionally rendered.
</div>
</template>
<script>
export default {
data() {
return {
isVisible: true
}
}
}
</script>
List Rendering
List rendering in Vue.js uses the `v-for` directive, which allows you to loop through an array or object and render an item for each iteration.
<template>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
]
}
}
}
</script>
Actions / Events / Custom Events
Vue.js uses the `v-on` directive to listen to DOM events and execute some JavaScript when triggered. Custom events allow communication between child and parent components.
<template>
<button @click="handleClick">Click me</button>
</template>
<script>
export default {
methods: {
handleClick() {
console.log('Button clicked!');
}
}
}
</script>
Lifecycle Hooks
Vue.js provides lifecycle hooks that allow you to add code at specific stages of the component instance lifecycle, such as `created`, `mounted`, `updated`, and `destroyed`.
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello, World!'
}
},
mounted() {
console.log('Component has been mounted!');
}
}
</script>
Slots
Slots are placeholders in a component, allowing you to pass content from a parent to a child component.
<template>
<div>
<slot></slot>
</div>
</template>
<script>
export default {
name: 'CustomComponent'
}
</script>
Configuration Scope
Configuration scope in Vue.js allows you to configure various aspects of a component, such as props, data, methods, and computed properties.
<template>
<div>{{ greeting }}</div>
</template>
<script>
export default {
props: ['name'],
computed: {
greeting() {
return `Hello, ${this.name}!`
}
}
}
</script>
Composition API
The Composition API is a set of APIs that allows you to use Vue.js features such as reactive state, lifecycle hooks, and watchers more flexibly.
<template>
<div>{{ count }}</div>
<button @click="increment">Increment</button>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
const increment = () => {
count.value++;
};
return {
count,
increment
};
}
}
</script>
Bind Data Between Child & Parent
Binding data between a parent and child component is done using props for passing data down and events for passing data up.
<!-- ParentComponent.vue -->
<template>
<ChildComponent :message="parentMessage" @update="updateMessage" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
data() {
return {
parentMessage: 'Hello from parent'
}
},
methods: {
updateMessage(newMessage) {
this.parentMessage = newMessage;
}
},
components: {
ChildComponent
}
}
</script>
<!-- ChildComponent.vue -->
<template>
<div>
<p>{{ message }}</p>
<button @click="changeMessage">Change Message</button>
</div>
</template>
<script>
export default {
props: ['message'],
methods: {
changeMessage() {
this.$emit('update', 'Hello from child');
}
}
}
</script>
Dynamic Components
Dynamic components can be dynamically changed based on a condition or user input using the `component` element and `:is` attribute.
<template>
<component :is="currentComponent"></component>
<button @click="toggleComponent">Toggle Component</button>
</template>
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
data() {
return {
currentComponent: 'ComponentA'
}
},
methods: {
toggleComponent() {
this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' :
'ComponentA';
}
},
components: {
ComponentA,
ComponentB
}
}
</script>
Computed Properties / Filters
Computed properties are used to compute derived states based on reactive data. Filters are used to apply common text formatting.
<template>
<div>{{ reversedMessage }}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello, World!'
}
},
computed: {
reversedMessage() {
return this.message.split('').reverse().join('');
}
}
}
</script>
watchEffect()
The `watchEffect` function automatically re-runs a given effect whenever the reactive state it depends on changes.
<template>
<div>{{ count }}</div>
<button @click="increment">Increment</button>
</template>
<script>
import { ref, watchEffect } from 'vue';
export default {
setup() {
const count = ref(0);
watchEffect(() => {
console.log(`Count is: ${count.value}`);
});
const increment = () => {
count.value++;
};
return {
count,
increment
};
}
}
</script>
Template Refs
Template refs directly access DOM elements or child components in your Vue instance.
<template>
<div>
<input ref="inputRef" />
<button @click="focusInput">Focus Input</button>
</div>
</template>
<script>
export default {
methods: {
focusInput() {
this.$refs.inputRef.focus();
}
}
}
</script>
Functional Component
Functional components are stateless and instance-less components. They are created by defining a `functional` attribute in the component’s options.
<template functional>
<div>{{ props.message }}</div>
</template>
<script>
export default {
functional: true,
props: {
message: String
},
render(h, context) {
return h('div', context.props.message);
}
}
</script>
Wrapping it Up
With its many advantages; Vue.js is a powerful front-end development framework. Its responsive data binding, component-based design, and robust community support foster an atmosphere that boosts efficiency and productivity.
Vue.js’s performance optimizations; integration capabilities; and powerful developer tools add to its allure. Whether you’re beginning a new project or trying to improve an old one; Vue.js has everything you need to build strong, high-performance apps.