DEV Community

Cover image for Vue cheat sheet 3 (advanced)
Adnan Babakan (he/him)
Adnan Babakan (he/him)

Posted on • Edited on

Vue cheat sheet 3 (advanced)

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

There is a Japanese version of this article available at https://qiita.com/_masa_u/items/d53275218cd381e1a810 Thanks to

Enjoy!

Table of content

Mixins

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:

// define a mixin object
export const myMixin = {
  created: function () {
    this.hello()
  },
  methods: {
    hello: function () {
      console.log('Hello from mixin!')
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

<script>
    import { myMixin } from './myMixin.js';
    export default {
        mixins: [myMixin]
    }
</script>
Enter fullscreen mode Exit fullscreen mode

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

Mixin option merging

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:

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" }
  }
})
Enter fullscreen mode Exit fullscreen mode

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

Global mixins

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

import Vue from 'vue';

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

const app = new Vue({
    el: '#app'
});
Enter fullscreen mode Exit fullscreen mode

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

Custom directives

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:

<script>
    export default {
        directives: {
            focus: {
                inserted: function (el) {
                    el.focus()
                }
            }
        }
    }
</script>
Enter fullscreen mode Exit fullscreen mode

The focus directive will be available as v-focus and can be used like this:

<input v-focus />
Enter fullscreen mode Exit fullscreen mode

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

Custom global directives

In order for your custom directives to be available throughout your Vue instance and globally you can define it like below:

Vue.directive('focus', {
  inserted: function (el) {
    el.focus()
  }
})
Enter fullscreen mode Exit fullscreen mode

Filters

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:

<script>
    export default {
        filters: {
            capitalize: function(value) {
                if (!value) return '';
                value = value.toString();
                return value.charAt(0).toUpperCase() + value.slice(1);
            }
        }
    };
</script>
Enter fullscreen mode Exit fullscreen mode

Then the capitalize filter can be used as below:

<span>{{ msg | capitalize }}</span>
Enter fullscreen mode Exit fullscreen mode

Or in a v-bind as below:

<a v-bind:href="url | capitalize">My capitalized link!</a>
Enter fullscreen mode Exit fullscreen mode

Global filters

Global filters are no different than normal filters but they will be defined once and can be used in every Vue instance or component.

import Vue from 'vue';

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

Router

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

Getting started with router

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

Router installation

It is recommended to install it using npm:

npm i vue-router --save
Enter fullscreen mode Exit fullscreen mode

It can be installed by including the file as well:

<script src="/path/to/vue.js"></script>
<script src="/path/to/vue-router.js"></script>
Enter fullscreen mode Exit fullscreen mode

After installing it, it is time to tell Vue to use the router. To do so you can do as below:

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);
Enter fullscreen mode Exit fullscreen mode

Your components which are bound to routes should be rendered somewhere in your page. This be declared as below:

<div id="app">
    <div>
        Hello World!
    </div>
    <router-view></router-view>
</div>
Enter fullscreen mode Exit fullscreen mode

Defining routes

Each route will have its own unique component bound. You can define your routes as below:

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`
});
Enter fullscreen mode Exit fullscreen mode

If you want yo push the routes to history of user's browser you should activate the history mode as below:

const router = new VueRouter({
  mode: 'history',
  routes // short for `routes: routes`
});
Enter fullscreen mode Exit fullscreen mode

And then attach your routes to your view instance:

const app = new Vue({
  router
}).$mount('#app');
Enter fullscreen mode Exit fullscreen mode

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

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:

<router-link to="/foo">Go to foo</router-link>
Enter fullscreen mode Exit fullscreen mode

Advanced routing

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

Dynamic routes

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):

const routes = [
  { path: '/user/:username', component: require('./path/to/user/component') },
];
Enter fullscreen mode Exit fullscreen mode

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:

<div>This is {{ $route.params.username }}'s profile!</a>
Enter fullscreen mode Exit fullscreen mode
Reacting to dynamic routes' param changes

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:

<script>
  export default {
    watch: {
      $route(to, from) {

      }
    }
  };
</script>
Enter fullscreen mode Exit fullscreen mode

404 route

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:

const routes = [
    // ... Any other routes ...
    { path: '*', component: require('./path/to/404/component') },
];
Enter fullscreen mode Exit fullscreen mode

Asterisk routes

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:

const routes = [
    { path: '/user-*', component: require('./path/to/user/component') },
];
Enter fullscreen mode Exit fullscreen mode

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

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

Imagine you have a pattern like this:

const routes = [
  {
    path: '/user/profile/setting/',
    component: require('./path/to/user/component')
  }
];
Enter fullscreen mode Exit fullscreen mode

You can define a name for it like this:

const routes = [
  {
    path: '/user/profile/setting/',
    component: require('./path/to/user/component'),
    name: 'settings'
  }
];
Enter fullscreen mode Exit fullscreen mode

Now your links can be like this:

<router-link :to='{name: "settings"}'>
    Profile settings
</router-link>
Enter fullscreen mode Exit fullscreen mode

Instead of this:

<router-link to="/user/profile/setting/">
    Profile settings
</router-link>
Enter fullscreen mode Exit fullscreen mode

Note: When passing an object to to attribute you should bind it.

Named routes with params

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:

const routes = [
  {
    path: '/posts/from/:username',
    component: require('./path/to/posts/component'),
  }
];
Enter fullscreen mode Exit fullscreen mode

You can have this:

const routes = [
  {
    path: '/posts/from/:username',
    component: require('./path/to/posts/component'),
    name: 'posts'
  }
];
Enter fullscreen mode Exit fullscreen mode

And in order to create a link for this you can have the code below:

<router-link :to='{name: "posts", params: {username: "adnanbabakan"}}'>
    Profile settings
</router-link>
Enter fullscreen mode Exit fullscreen mode

Programmatic navigation

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:

router.push('/foo');
Enter fullscreen mode Exit fullscreen mode

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

You can also use router.push() for named routes like this:

router.push({name: 'myRoute'});
Enter fullscreen mode Exit fullscreen mode

Programmatic navigation with params

As well, router.push() can be used for redirecting with params, like this:

router.push({name: 'myRoute', params: {paramOne: 'Hello', paramTwo: 'Salam'}});
Enter fullscreen mode Exit fullscreen mode

Route redirection

Routes can be defined to be redirected to each other. Like this:

const routes = [
  {
    path: '/foo',
    redirect: '/bar'
  }
];
Enter fullscreen mode Exit fullscreen mode

Route named redirection

A route can also be redirected to a named route, like this:

const routes = [
  {
    path: '/foo',
    redirect: { name: 'myRoute' }
  }
];
Enter fullscreen mode Exit fullscreen mode

Dynamic route redirection

A route can be redirected using a function to evaluate the destination, like this:

const routes = [
  {
    path: '/foo',
    redirect: to => {
      // the function receives the target route as the argument
      // return redirect path/location here.
    }
  }
];
Enter fullscreen mode Exit fullscreen mode

Route redirection with params

If the target route has a param it can be passed to the destination as well:

const routes = [
  {
    path: '/profile/:username',
    redirect: '/user/:username'
  }
];
Enter fullscreen mode Exit fullscreen mode

Route alias

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

For example:

const routes = [
  {
    path: '/foo',
    alias: '/bar'
  }
];
Enter fullscreen mode Exit fullscreen mode

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

A route can have multiple aliases as well:

const routes = [
  {
    path: '/foo',
    alias: ['/bar', '/baz']
  }
];
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)