Vue cheat sheet 3 (advanced)
Tags: vue, webdev, tutorial
Published: 2020-01-02 12:57:35

Hey DEV.to community!

So since Vue cheat sheet series got lots of attention I decided to continue publishing these series and this one will be a little bit more advanced since almost all major beginner things are covered in the previous ones.

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/d53275218cd381e1a810](https://qiita.com/_masa_u/items/d53275218cd381e1a810) Thanks to {% user masa_u %}

Enjoy!

# Table of content
* [Mixins](#mixins)
    * [Mixin option merging](#mixin-option-merging)
    * [Global mixins](#global-mixins)
* [Custom directives](#custom-directives)
    * [Custom global directives](#custom-global-directives)
* [Filters](#filters)
    * [Global filters](#global-filters)
* [Router](#router)
    * [Getting started with router](#getting-started-with-router)
      * [Router installation](#router-installation)
      * [Defining routes](#defining-routes)
    * [Router links](#router-links)
    * [Advanced routing](#advanced-routing)
      * [Dynamic routes](#dynamic-routes)
          * [Reacting to dynamic routes param changes](#reacting-to-dynamic-routes-param-changes)
      * [404 route](#404-route)
      * [Asterisk routes](#asterisk-routes)
    * [Named routes](#named-routes)
      * [Named routes with params](#named-routes-with-params)
    * [Programmatic navigation](#programmatic-navigation)
      * [Programmatic named navigation](#programmatic-named-navigation)
      * [Programmatic navigation with params](#programmatic-navigation-with-params)
    * [Route redirection](#route-redirection)
      * [Route named redirection](#route-named-redirection)
      * [Dynamic route redirection](#dynamic-route-redirection)
      * [Route redirection with params](#route-redirection-with-params)
    * [Route alias](#route-alias)

## Mixins <a name="mixins"></a>

To be simple, mixins are just parts of your component stored in a separate file son it can be used again in other components.

A mixin can look like this:
```javascript
// define a mixin object
export const myMixin = {
  created: function () {
    this.hello()
  },
  methods: {
    hello: function () {
      console.log('Hello from mixin!')
    }
  }
}
```

As you see this has a `created` hook and a method called `hello` so now this mixing can be used in a component, like below:
```vue
<script>
    import { myMixin } from './myMixin.js';
    export default {
        mixins: [myMixin]
    }
</script>
```

So this will function as if you wrote those hooks and methods in this component.

### Mixin option merging <a name="mixin-option-merging"></a>

Well in case of any conflicts between a components self-assigned properties or methods and the mixin's, the component it self will be in priority, see this:
```javascript
let mixin = {
  data: function () {
    return {
      message: 'hello',
      foo: 'abc'
    }
  }
}

new Vue({
  mixins: [mixin],
  data: function () {
    return {
      message: 'goodbye',
      bar: 'def'
    }
  },
  created: function () {
    console.log(this.$data)
    // => { message: "goodbye", foo: "abc", bar: "def" }
  }
})
```

The way Vue handles overwriting can be changed but we will cover that in the other cheat sheet.

### Global mixins <a name="global-mixins"></a>

A global mixin is no different than a normal mixin rather than its affection scope which will include all Vue instances created.

```javascript
import Vue from 'vue';

Vue.mixin({
    methods: {
        sayHi() {
            alert('Salam!');
        }
    }
});

const app = new Vue({
    el: '#app'
});
```

The method `sayHi` will be available for every component and Vue instance in the code above.

## Custom directives <a name="custom-directives"></a>

As you know directives are the way Vue handles DOM. For instance `v-model` or `v-show` are directives.

In order to define a directive you can do as below:

```vue
<script>
    export default {
        directives: {
            focus: {
                inserted: function (el) {
                    el.focus()
                }
            }
        }
    }
</script>
```

The `focus` directive will be available as `v-focus` and can be used like this:
```vue
<input v-focus />
```

So the input will be focused as soon as the component renders.

### Custom global directives <a name="custom-global-directives"></a>

In order for your custom directives to be available throughout your Vue instance and globally you can define it like below:
```javascript
Vue.directive('focus', {
  inserted: function (el) {
    el.focus()
  }
})
```

## Filters <a name="filters"></a>

Filters are simply used to alter a value and return it.
They can be used in both mustaches and v-bind directive.

To define a filter in a component you can de as below:
```vue
<script>
    export default {
        filters: {
            capitalize: function(value) {
                if (!value) return '';
                value = value.toString();
                return value.charAt(0).toUpperCase() + value.slice(1);
            }
        }
    };
</script>
```

Then the capitalize filter can be used as below:
```vue
<span>{{ msg | capitalize }}</span>
```

Or in a v-bind as below:
```vue
<a v-bind:href="url | capitalize">My capitalized link!</a>
```

### Global filters <a name="global-filters"></a>

Global filters are no different than normal filters but they will be defined once and can be used in every Vue instance or component.
```javascript
import Vue from 'vue';

Vue.filter('focus', {
    capitalize: function(value) {
        if (!value) return '';
        value = value.toString();
        return value.charAt(0).toUpperCase() + value.slice(1);
    }
});
```

## Router <a name="router"></a>

Vue router is used to design a routing system on the client-side using Vue.

### Getting started with router <a name="getting-started-with-router"></a>

In order to start using the router you need to install it. These are steps:

#### Router installation <a name="router-installation"></a>

It is recommended to install it using npm:
```bash
npm i vue-router --save
```

It can be installed by including the file as well:
```html
<script src="/path/to/vue.js"></script>
<script src="/path/to/vue-router.js"></script>
```

After installing it, it is time to tell Vue to use the router. To do so you can do as below:
```javascript
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);
```

Your components which are bound to routes should be rendered somewhere in your page. This be declared as below:
```html
<div id="app">
    <div>
        Hello World!
    </div>
    <router-view></router-view>
</div>
```

#### Defining routes <a name="defining-routes"></a>

Each route will have its own unique component bound. You can define your routes as below:
```javascript
const routes = [
  { path: '/foo', component: require('./path/to/foo/component') },
  { path: '/bar', component: require('./path/to/bar/component') }
];

const router = new VueRouter({
  routes // short for `routes: routes`
});
```

If you want yo push the routes to history of user's browser you should activate the history mode as below:
```javascript
const router = new VueRouter({
  mode: 'history',
  routes // short for `routes: routes`
});
```

And then attach your routes to your view instance:
```javascript
const app = new Vue({
  router
}).$mount('#app');
```

*__Note__*: If you are using the history mode, in order to redirect all your requests to your `index.html` file so Vue can take care of rest of it you should configure your web server. Unless, by refreshing the browser on a page, it will return 404 since that page actually doesn't exist on the server.

### Router links <a name="router-links"></a>

Router links are special since they don't refresh the page but only getting the component that is needed (and push the URL to the history in history mode) so it seems like a new page.

Instead of a hyper-link (`a` tag) you should use `router-link` as below:
```vue
<router-link to="/foo">Go to foo</router-link>
```

### Advanced routing <a name="advanced-routing"><a>

Vue router is beyond just few simple routes and it provides some great ways of handling routes.

#### Dynamic routes <a name="dynamic-routes"></a>

Dynamic routes are used to match a series of routes with some params to be acquired.

A dynamic route is defined just like a normal route but with a colon at the beginning of the dynamic segment(s):
```javascript
const routes = [
  { path: '/user/:username', component: require('./path/to/user/component') },
];
```

Now by the route above all of links such as `/user/adnanbabakan`, `/user/dev/` or `/user/vue` is valid.

The `username` can be accessed in the route component as below:
```vue
<div>This is {{ $route.params.username }}'s profile!</a>
``` 

##### Reacting to dynamic routes' param changes <a name="reacting-to-dynamic-routes-param-changes"></a>

Considering the example above. If the user moves from `/user/adnanbabakan` to `/user/dev` Vue won't destroy the previous instance since it is already going to be the same component rendered again, thus the lifecycle hooks won't be called in order to react to any params changes you can watch the `$route` object like 
this:
```vue
<script>
  export default {
    watch: {
      $route(to, from) {

      }
    }
  };
</script>
```

#### 404 route <a name="404-route"></a>

Every website needs a great 404 route. In a Vue Router we can define an asterisk `*` route at the end so it catches everything that is not defined.

*__Warning__*: The asterisk route should be defined at the end and after any other route. Unless it will match everything else and ruin your routing system.

In order to do so look at the code below:
```javascript
const routes = [
    // ... Any other routes ...
    { path: '*', component: require('./path/to/404/component') },
];
```

#### Asterisk routes <a name="asterisk-routes"></a>

Asterisks can be used to match another kind of dynamic routes. A dynamic route can only match the dynamic segments between two slashes `/` but asterisk can do beyond that.

Look at the route below:
```javascript
const routes = [
    { path: '/user-*', component: require('./path/to/user/component') },
];
```

So by the route above routes such as `/user-adnan` and `/user-dev` can be rendered.

By using the route below the `$route.params` will have a property called `pathMatch` which will include the part that matched the asterisk.
For example `$route.params.pathMatch` in the page `/user-adnan` will return `adnan`.

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

Named routes are used to access long route pattern with their shorter name.

Imagine you have a pattern like this:
```javascript
const routes = [
  {
    path: '/user/profile/setting/',
    component: require('./path/to/user/component')
  }
];
```

You can define a name for it like this:
```javascript
const routes = [
  {
    path: '/user/profile/setting/',
    component: require('./path/to/user/component'),
    name: 'settings'
  }
];
```

Now your links can be like this:
```vue
<router-link :to='{name: "settings"}'>
    Profile settings
</router-link>
```

Instead of this:
```vue
<router-link to="/user/profile/setting/">
    Profile settings
</router-link>
```

*__Note__*: When passing an object to `to` attribute you should bind it.


#### Named routes with params <a name="named-routes-with-params"></a>

Some routes might have params as we had some examples above. You can define a name for them as well.

For example for the route below:
```javascript
const routes = [
  {
    path: '/posts/from/:username',
    component: require('./path/to/posts/component'),
  }
];
```

You can have this:
```javascript
const routes = [
  {
    path: '/posts/from/:username',
    component: require('./path/to/posts/component'),
    name: 'posts'
  }
];
```

And in order to create a link for this you can have the code below:
```vue
<router-link :to='{name: "posts", params: {username: "adnanbabakan"}}'>
    Profile settings
</router-link>
```

### Programmatic navigation <a name="programmatic-navigation"></a>

As you read before in this cheat sheet you can create a router link using `<router-link></router-link>` but what if you needed to redirect user programmatically? Well you can do that by this code:
```javascript
router.push('/foo');
```

This code will redirect your user to `/foo`. This is especially used in a condition or other situations like redirection after login.

#### Programmatic named navigation <a name="programmatic-named-navigation"></a>

You can also use `router.push()` for named routes like this:
```javascript
router.push({name: 'myRoute'});
```

#### Programmatic navigation with params <a name="programmatic-navigation-with-params"></a>

As well, `router.push()` can be used for redirecting with params, like this:
```javascript
router.push({name: 'myRoute', params: {paramOne: 'Hello', paramTwo: 'Salam'}});
```

### Route redirection <a name="route-redirection"></a>

Routes can be defined to be redirected to each other. Like this:
```javascript
const routes = [
  {
    path: '/foo',
    redirect: '/bar'
  }
];
```

#### Route named redirection <a name="route-named-redirection"></a>

A route can also be redirected to a named route, like this:
```javascript
const routes = [
  {
    path: '/foo',
    redirect: { name: 'myRoute' }
  }
];
```

#### Dynamic route redirection <a name="dynamic-route-redirection"></a>

A route can be redirected using a function to evaluate the destination, like this:
```javascript
const routes = [
  {
    path: '/foo',
    redirect: to => {
      // the function receives the target route as the argument
      // return redirect path/location here.
    }
  }
];
```

#### Route redirection with params <a name="route-redirection-with-params"></a>

If the target route has a param it can be passed to the destination as well:
```javascript
const routes = [
  {
    path: '/profile/:username',
    redirect: '/user/:username'
  }
];
```

### Route alias <a name="route-alias"></a>

A route alias means a route can have multiple addressed to be accessed from.

For example:
```javascript
const routes = [
  {
    path: '/foo',
    alias: '/bar'
  }
];
```

Now the route `/foo` can be accessed as `/bar/` as well.

A route can have multiple aliases as well:
```javascript
const routes = [
  {
    path: '/foo',
    alias: ['/bar', '/baz']
  }
];
```

---

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

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