Vue cheat sheet 2
Tags: vue, webdev, tutorial
Published: 2019-12-26 16:18:13

Hey there DEV.to community!

So this is the second part of my previous Vue cheat sheet.

Some descriptions and code samples are from Vue.js official website. [Visit Vue.js](https://vuejs.org/)

There is a Japanese version of this article available at [https://qiita.com/_masa_u/items/44db6af7dc0bc48bcc14](https://qiita.com/_masa_u/items/44db6af7dc0bc48bcc14) Thanks to {% user masa_u %}

Enjoy!

# Table of content
* [Lifecycle hooks](#lifecycle-hooks)
    * [Before create hook](#before-create-hook)
    * [Created hook](#created-hook)
    * [Before mount hook](#before-mount-hook)
    * [Mounted hook](#mounted-hook)
    * [Before update hook](#before-update-hook)
    * [Updated hook](#updated-hook)
    * [Before destroy hook](#before-destroy-hook)
    * [Destroyed hook](#destroyed-hook)
* [Events](#events)
    * [Available events](#available-events)
    * [Event modifiers](#event-modifiers)
      * [Stop modifier](#stop-modifier)
      * [Prevent modifier](#prevent-modifier)
      * [Capture modifier](#capture-modifier)
      * [Once modifier](#once-modifier)
      * [Self modifier](#self-modifier)
      * [Passive modifier](#passive-modifier)
    * [Key modifiers](#key-modifiers)
      * [Enter key modifier](#enter-key-modifier)
      * [Tab key modifier](#tab-key-modifier)
      * [Delete key modifier](#delete-key-modifier)
      * [Esc key modifier](#esc-key-modifier)
      * [Space key modifier](#space-key-modifier)
      * [Up key modifier](#up-key-modifier)
      * [Down key modifier](#down-key-modifier)
      * [Right key modifier](#right-key-modifier)
      * [Left key modifier](#left-key-modifier)
      * [Home key modifier](#home-key-modifier)
      * [End key modifier](#end-key-modifier)
      * [Ctrl key modifier](#ctrl-key-modifier)
      * [Alt key modifier](#alt-key-modifier)
      * [Shift key modifier](#shift-key-modifier)
      * [Meta key modifier](#meta-key-modifier)
      * [Custom key modifier](#custom-key-modifier)
    * [Key modifiers combination](#key-modifiers-combination)
    * [Exact key modifier](#exact-key-modifier)
* [Components](#components)
    * [Single file component](#single-file-component)
    * [Registering components](#registering-components)
      * [Global component registration](#global-component-registration)
      * [Instance scoped component registration](#instance-scoped-component -registration)
      * [Lazy load component registration](#lazy-load-component-registration)
    * [Component props](#component-props)
    * [Component slots](#component-slots)
      * [Simple slot](#simple-slot)
      * [Named slots](#named-slots)
      * [Scoped slots](#scoped-slots)

## Lifecycle hooks <a name="lifecycle-hooks"></a>

Lifecycle hooks are simply some functions that run on a specific event/time during your Vue component.

### Before create hook <a name="before-create-hook"></a>

Called synchronously immediately after the instance has been initialized, before data observation and event/watcher setup.

Sample:
```javascript
let app = new Vue({
	beforeCreate() {
		console.log('I\'m not created yet');
	}
});
```

### Created hook <a name="created-hook"></a>

Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.

Sample:
```javascript
let app = new Vue({
	created() {
		console.log('I\'m created');
	}
});
```

### Before mount hook <a name="before-mount-hook"></a>

Called right before the mounting begins: the render function is about to be called for the first time.

*__Note__*: This hook is not called during server-side rendering.

Sample:
```javascript
let app = new Vue({
	beforeMount() {
		console.log('Let\'s begin!');
	}
});
```

### Mounted hook <a name="mounted-hook"></a>

Called after the instance has been mounted, where `el` is replaced by the newly created `vm.$el`. If the root instance is mounted to an in-document element, `vm.$el` will also be in-document when mounted is called.

*__Note__*: This hook is not called during server-side rendering.

Sample:
```javascript
let app = new Vue({
	mounted() {
		console.log('I\'m ready!');
	}
});
```

### Before update hook <a name="before-update-hook"></a>

Called when data changes, before the DOM is patched. This is a good place to access the existing DOM before an update, e.g. to remove manually added event listeners.

*__Note__*: This hook is not called during server-side rendering, because only the initial render is performed server-side.

Sample:
```javascript
let app = new Vue({
	beforeUpdate() {
		console.log('Your DOM is about to change. Be careful!');
	}
});
```

### Updated hook <a name="updated-hook"></a>

Called after a data change causes the virtual DOM to be re-rendered and patched.

The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here. However, in most cases you should avoid changing state inside the hook. To react to state changes, it’s usually better to use a computed property or watcher instead.

*__Note__*: This hook is not called during server-side rendering.

Sample:
```javascript
let app = new Vue({
	updated() {
		console.log('Hello new DOM!');
	}
});
```

### Before destroy hook <a name="before-destroy-hook"></a>

Called right before a Vue instance is destroyed. At this stage the instance is still fully functional.

*__Note__*: This hook is not called during server-side rendering.

Sample:
```javascript
let app = new Vue({
	beforeDestroy() {
		console.log('Well it\'s the time I think...');
	}
});
```

### Destroyed hook <a name="destroyed-hook">

Called after a Vue instance has been destroyed. When this hook is called, all directives of the Vue instance have been unbound, all event listeners have been removed, and all child Vue instances have also been destroyed.

*__Note__*: This hook is not called during server-side rendering.

Sample:
```javascript
let app = new Vue({
	destroyed() {
		console.log('BOOOOM!');
	}
});
```

## Events <a name="events"></a>

Events are called when a specific action is performed on an element.

__In the previous Vue cheat sheet I described them really basically. Here I will describe more aspects of events.__

Keep in mind that `@` is a short hand of `v-on:`.

### Available events <a name="available-events"></a>

By using `v-on` you can access all JavaScript events. These are some samples:
```vue
<button @click="() => alert('Hello')">Do it</button>
<button @mouseover="() => alert('Hello')">Do it</button>
<button @mouseout="() => alert('Hello')">Do it</button>
<button @contextmenu="() => alert('Hello')">Do it</button>
```

You can also `submit` event on forms:
```vue
<form @submit="() => alert('This form is submitted')">
    <input type="text" />
</form>
```

### Event modifiers <a name="event-modifiers"></a>

Event modifiers are used to alter some behaviour of the event or have a more control on it.

Modifiers are added following by a `.` after the event.

So this is the structure `v-on:event.modifier` or `@event.modifier`.

Modifiers can also be chained to be performed at the respective order, like: `@event.modifier-one.modifier-two`

#### Stop modifier <a name="stop-modifier"></a>

```vue
<!-- the click event's propagation will be stopped -->
<a v-on:click.stop="doThis"></a>
```

#### Prevent modifier <a name="prevent-modifier"></a>

```vue
<!-- the submit event will no longer reload the page -->
<form v-on:submit.prevent="onSubmit"></form>
```

#### Capture modifier <a name="capture-modifier"></a>

```vue
<!-- use capture mode when adding the event listener -->
<!-- i.e. an event targeting an inner element is handled here before being handled by that element -->
<div v-on:click.capture="doThis">...</div>
```

#### Once modifier <a name="once-modifier"></a>

```vue
<!-- the click event will be triggered at most once -->
<a v-on:click.once="doThis"></a>
```

#### Self modifier <a name="self-modifier"></a>

```vue
<!-- only trigger handler if event.target is the element itself -->
<!-- i.e. not from a child element -->
<div v-on:click.self="doThat">...</div>
```

#### Passive modifier <a name="passive-modifier"></a>

```vue
<!-- the scroll event's default behavior (scrolling) will happen -->
<!-- immediately, instead of waiting for `onScroll` to complete  -->
<!-- in case it contains `event.preventDefault()`                -->
<div v-on:scroll.passive="onScroll">...</div>
```

### Key modifiers

Listening to keyboards event is easy but detecting which key is pressed would need the key code. Vue has some modifiers in order to listen to a specific key when using keyboard events.

These modifiers can be used with any key events such as `keydown` or `keyup`

#### Enter key modifier <a name="enter-key-modifier"></a>

```vue
<input @keydown.enter="() => alert('Hey there!')"></input>
```

#### Tab key modifier <a name="tab-key-modifier"></a>

```vue
<input @keydown.tab="() => alert('Hey there!')"></input>
```

#### Delete key modifier <a name="delete-key-modifier"></a>

```vue
<input @keydown.delete="() => alert('Hey there!')"></input>
```

#### Esc key modifier <a name="esc-key-modifier"></a>

```vue
<input @keydown.esc="() => alert('Hey there!')"></input>
```

#### Space key modifier <a name="space-key-modifier"></a>

```vue
<input @keydown.space="() => alert('Hey there!')"></input>
```

#### Up key modifier <a name="up-key-modifier"></a>

```vue
<input @keydown.up="() => alert('Hey there!')"></input>
```

#### Down key modifier <a name="down-key-modifier"></a>

```vue
<input @keydown.down="() => alert('Hey there!')"></input>
```

#### Right key modifier <a name="right-key-modifier"></a>

```vue
<input @keydown.right="() => alert('Hey there!')"></input>
```

#### Left key modifier <a name="left-key-modifier"></a>

```vue
<input @keydown.left="() => alert('Hey there!')"></input>
```

#### Home key modifier <a name="home-key-modifier"></a>

```vue
<input @keydown.home="() => alert('Hey there!')"></input>
```

#### End down key modifier <a name="end-key-modifier"></a>

```vue
<input @keydown.end="() => alert('Hey there!')"></input>
```

#### Ctrl down key modifier <a name="end-key-modifier"></a>

```vue
<input @keydown.ctrl="() => alert('Hey there!')"></input>
```

#### Alt down key modifier <a name="alt-key-modifier"></a>

```vue
<input @keydown.alt="() => alert('Hey there!')"></input>
```

#### Shift down key modifier <a name="shift-key-modifier"></a>

```vue
<input @keydown.shift="() => alert('Hey there!')"></input>
```

#### Meta down key modifier <a name="meta-key-modifier"></a>

```vue
<input @keydown.meta="() => alert('Hey there!')"></input>
```

#### Custom key code <a name="custom-key-modifier"></a>

If Vue doesn't provide an alias for the key you want, you can use its key code as below:
```vue
<input @keydown.49="() => alert('Hey there!')"></input>
```
__Key code 49 is for the number 1 on top of keyboard. (Not the number pad)__

### Key modifiers combination <a name="#key-modifiers-combination"></a>

You can chain key modifiers in order to create a combined structure, like this:
```vue
<input @keydown.ctrl.shift="() => alert('Hey there!')"></input>
```

### Exact key modifier <a name="exact-key-modifier"></a>

Using `exact` will allow you to capture the button you need and nothing else can be combined.

By using the code below if you hold shift and press ctrl it will respond normally:
```vue
<input @keydown.ctrl="() => alert('Hey there!')"></input>
```

But by using the code below the only key which should be pressed is ctrl:
```vue
<input @keydown.exact.ctrl="() => alert('Hey there!')"></input>
```

## Components <a name="components"></a>

Components are reusable Vue instances used to simplify your code and split your code in a better manner.

This is a Vue component:
```javascript
Vue.component('button-counter', {
  data: function () {
    return {
      count: 0
    }
  },
  template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
```

As you can it has its template embedded in it as well as the data it uses and can be used in other Vue components like this:
```vue
<div id="components-demo">
  <button-counter></button-counter>
  <button-counter></button-counter>
  <button-counter></button-counter>
</div>
```

This will render three different buttons which has nothing to do with each other. Each of them will function separately and each has its own `count` data.

*__Important__*: When defining a component the `data` should be a function returning an object if not each instance won't have its own data and it will be shared.

### Single file component <a name="single-file-component"></a>

A single file component (or SFC) is a component which is in one file (holy crap! really?).

It has more clean syntax and it is as below:
```vue
<template>
    <div>

    </div>
</template>

<script>
	export default {

	};
</script>

<style scoped>

</style>
```

### Registering components <a name="registering-components"></a>

By registering components you can use them inside your templates.

#### Global component registration <a name="global-component-registration"></a>

By doing this method your component will be available in every Vue instance (in case you have more than one):
```javascript
import Vue from 'vue';

Vue.component('my-component', require('/path/to/your/component'));
```

#### Instance scoped registration <a name="instance-scoped-component-registration"></a>

By doing this the component will only be available in the specified Vue instance:
```javascript
import Vue from 'vue';

const myComponent = require('/path/to/your/component');

let app = new Vue({
	components: {
	    myComponent
	}
});
```

#### Lazy load component registration <a name="lazy-load-component-registration"></a>

This method is pretty cool since it will not bundle your component with your main entry file thus your website will be loaded faster and only the needed components will be required.

```javascript
import Vue from 'vue';

const myComponent = () => import('./components/myComponent ');

let app = new Vue({
	components: {
	    myComponent 
	}
});
```

*__Bonus Tip__*: This will extract your components named by numbers from 0 and so on. If you are using webpack you can use a magic comment in order to change your components' file names like below:
```javascript
import Vue from 'vue';

const myComponent = () => import(/* webpackChunkName: "myComponent" */ './components/myComponent ');

let app = new Vue({
	components: {
	    myComponent 
	}
});
```

### Component props <a name="component-props"></a>

Components can have props which act literally like HTML tags' attributes.

By having a component like this:
```javascript
Vue.component('blog-post', {
  props: ['postTitle'],
  template: '<h3>{{ postTitle }}</h3>'
})
```

You can use it like this:
```vue
<blog-post post-title="hello!"></blog-post>
```

*__Note__*: When defining props it is better to define it using camelCase but when using it, use it as kebab-case. Although it is possible to use kebab-case defined props as camelCase in Vue but IDEs might get confused about it.

Your single file components can also have props:
```vue
<template>
    <div>

    </div>
</template>

<script>
	export default {
	       props: ['myProp'];
	};
</script>

<style scoped>

</style>
```

### Component slots <a name="component-slots"></a>

Slots are used to embed other elements or components inside a component.

#### Simple slot <a name="simple-slot"></a>

A simple slot is an unnamed slot and is used like below in a template:
```vue
<a :href="url" class="strange-class"><slot></slot></a>
```

After defining the template above assuming that the component name is `navigation-link` and `url` is a prop, you can use it as below:
```vue
<navigation-link url="/my-profile">Your profile</navigation-link>
```

As you see we have a text inside of our components and that is going to be inserted instead of `<slot></slot>`.

#### Named slots <a name="named-slots"></a>

Named slots are a little different than an unnamed one.

By defining a component called `base-layout` like this:
```vue
<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>
```

You can use it like this:
```vue
<base-layout>
  <template v-slot:header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template v-slot:footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>
```

The templates with `v-slot:slot-name` will be placed in their respective slots defined in the component and other ones will be placed in `<slot></slot>` which is unnamed.

*__Note__*: An unnamed slot is actually accessible with the name `default` like below:
```vue
<base-layout>
  <template v-slot:header>
    <h1>Here might be a page title</h1>
  </template>

  <template v-slot:default>
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </template>

  <template v-slot:footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>
```

#### Scoped slots <a named="scoped-slots"></a>

A slot can have access to its parents prop in order to avoid such a thing (if needed) you can define a slot prop like below:
```vue
<span>
  <slot v-bind:user="user">
    {{ user.lastName }}
  </slot>
</span>
```

And when using:
```vue
<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.user.firstName }}
  </template>
</current-user>
```

This slot will use the `user` available in the component and not the one available in the parent component.

---

Check out my free Node.js Essentials E-book here:

{% link https://dev.to/adnanbabakan/nodejs-essentials-free-e-book-5319 %}