Categories
JavaScript Vue

Simple Vue Libraries for Adding Input Controls

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at some simple Vue packages for adding rich input controls to our Vue apps.

vue-input-tag

The vue-input-tag package lets us add an input control to let users enter multiple tags.

We can install the Node package version by running:

npm install vue-input-tag --save

Also, we can include the library from a script tag by writing:

<script src="https://unpkg.com/vue-input-tag"></script>

Then we can use it as follows:

main.js

import Vue from "vue";  
import App from "./App.vue";  
import InputTag from "vue-input-tag";  
Vue.component("input-tag", InputTag);

Vue.config.productionTip = false;

new Vue({  
  render: h => h(App)  
}).$mount("#app");

App.vue

<template>  
  <div id="app">  
    <input-tag v-model="tags"></input-tag>  
    <p>{{tags}}</p>  
  </div>  
</template>

<script>  
export default {  
  name: "App",  
  data() {  
    return { tags: [] };  
  }  
};  
</script>

In the code above, we registered the vue-input-tag plugin in main.js . Then we just add the input-tag component from the package into our component.

In the component object, we have the data method that returns an object with the tags model, which is an array.

Then when we enter the tags, we see them displayed below the input.

In addition to the v-model directive to bind the data, it also takes the following props:

  • value — an array of tags to be rendered in the input
  • placeholder — a string for the placeholder
  • read-only — boolean to set the input to read-only
  • add-tag-on-blur — Boolean to indicate whether to add the tag when the input control loses focus
  • limit — string or number to set a limit on the number of tags
  • validate — validator for user input. We can choose from email , url , text , digits , or isodate , or we can pass in a function or regex object for custom validation
  • add-tag-on-keys — an array of keys that are going to be added to new tags
  • allow-duplicates — boolean to indicate whether we want to allow duplicate tags
  • before-adding — a sync or async function that lets us normalize tag before adding

We can use some of these props as follows:

<template>  
  <div id="app">  
    <input-tag v-model="tags" :before-adding="toUpperCase"></input-tag>  
    <p>{{tags}}</p>  
  </div>  
</template>

<script>  
export default {  
  name: "App",  
  data() {  
    return { tags: [] };  
  },  
  methods: {  
    toUpperCase(v) {  
      return v.toUpperCase();  
    }  
  }  
};  
</script>

In the code above, we added the toUpperCase method that converts whatever we entered to uppercase before setting the value in our model property.

So everything entered will become uppercase automatically.

vue-dropdowns

vue-dropdowns is a simple Vue package that lets us add a dropdown without writing all the code from scratch.

It’s very simple and doesn’t have many configuration options.

To install it, we run:

npm install vue-dropdowns

to install the Node package.

Then we can use it as follows:

App.vue :

<template>  
  <div id="app">  
    <dropdown  
      :options="arr"  
      :selected="object"  
      v-on:updateOption="onSelect"  
      placeholder="Select"  
      :closeOnOutsideClick="true"  
    ></dropdown>  
    <p>{{object}}</p>  
  </div>  
</template>

<script>  
import dropdown from "vue-dropdowns";

export default {  
  name: "App",  
  data() {  
    return {  
      arr: [  
        {  
          name: "Foo",  
          value: "foo"  
        },  
        {  
          name: "Bar",  
          value: "bar"  
        },  
        {  
          name: "Baz",  
          value: "baz"  
        },  
      ],  
      object: {}  
    };  
  }, 
  components: {  
    dropdown: dropdown  
  }, 
  methods: {  
    onSelect(payload) {  
      this.object = payload;  
    }  
  }  
};  
</script>

In the code above, we imported the dropdown component from the package. Then we added the onSelect method to set this.object to the value that’s selected from the dropdown.

In the data method, we return an object with an array of options for our dropdown. Each entry on arr has the name and value properties, where the name property’s value will be displayed from in the dropdown.

We set arr as the value of the options prop to populate the dropdown with the items from arr .

selected binds to the selected value, which is compared deeply instead of using === to do the comparison.

v-on:updateOption runs an event handler when an item is selected. In this case, it’ll be the onSelect method that we defined. The payload parameter has the selected item.

placeholder is the placeholder for the dropdown. closeOnOutsideClick is set to true so that it’ll close when we click outside.

Then when selecting something from the dropdown, we’ll see the object of the selected item displayed.

Conclusion

vue-input-tag provides us with an input control that lets us enter tags.

The vue-dropdowns package lets us add a dropdown with various options.

Categories
JavaScript Vue

Some Easy to Use Vue Data Grid Libraries

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at some easy to use data grid and table libraries to get you results faster.

vue-js-grid

This is a cool library that lets us create a data grid where the items in it are draggable and droppable.

It’s also very easy to create this effect. To install it, we run:

npm install --save vue-js-grid

Then we can use it as follows:

main.js :

import Vue from "vue";  
import App from "./App.vue";  
import Grid from "vue-js-grid";

Vue.use(Grid);  
Vue.config.productionTip = false;

new Vue({  
  render: h => h(App)  
}).$mount("#app");

App.vue :

<template>  
  <div id="app">  
    <grid :draggable="true" :sortable="true" :items="items" :height="100" :width="100">  
      <template slot="cell" scope="props">  
        <div>{{props.item}}</div>  
      </template>  
    </grid>  
  </div>  
</template>

<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      items: ["foo", "bar", "baz"]  
    };  
  }  
};  
</script>

In the code above, we imported the package into our app with Vue.use . Then we added the grid component to display the grid.

Then we set the items prop to items to display the items on our screen. Also, we set the draggable and sortable props to true so that we can drag the items around.

Other options that are available include, cellWidth and cellHeight . The component also emit the following events:

  • change — emitted when items are being rearranged
  • remove — emitted when n element is deleted
  • click — occurs when a cell is clicked
  • sort — emitted when array item is changed manually

The slot props have the following properties and methods in addition to item :

  • index — initial index of item
  • sort — the current index of the item after ordering
  • remove() — a method that’ll remove the item from the array and re-sort the list

vue-easytable

vue-easytable lets us create a table without too much code on the template.

All we have to do is include our table content data and column list and then set them as props for the component.

To install it, we run:

npm install vue-easytable

Then we add the code to use the package as follows:

main.js :

import Vue from "vue";  
import App from "./App.vue";  
import "vue-easytable/libs/themes-base/index.css";  
import { VTable, VPagination } from "vue-easytable";  
Vue.component(VTable.name, VTable);  
Vue.component(VPagination.name, VPagination);  
Vue.config.productionTip = false;

new Vue({  
  render: h => h(App)  
}).$mount("#app");

App.vue :

<template>  
  <div id="app">  
    <v-table :width="1000" :columns="columns" :table-data="tableData" :show-vertical-border="false"></v-table>  
  </div>  
</template>

<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      tableData: [  
        {  
          firstName: "Jane",  
          lastName: "Smith",  
          phone: "555-555-1212"  
        },  
        {  
          firstName: "Joe",  
          lastName: "Smith",  
          phone: "182-100-1538"  
        },  
        {  
          firstName: "Mary",  
          lastName: "Smith",  
          phone: "161-493-0097"  
        }  
      ],  
      columns: [  
        {  
          field: "firstName",  
          title: "First Name",  
          width: 100,  
          titleAlign: "left",  
          columnAlign: "left"  
        },  
        {  
          field: "lastName",  
          title: "Last Name",  
          width: 260,  
          titleAlign: "left",  
          columnAlign: "left"  
        },  
        {  
          field: "phone",  
          title: "Phone",  
          width: 330,  
          titleAlign: "left",  
          columnAlign: "left"  
        }  
      ]  
    };  
  }  
};  
</script>

We imported the package and register the components in main.js . Then we add the table data to the data field and then add the v-table to our template with the columns prop for adding the columns and the table-data prop for the table data.

We can also add a selection box as a column as follows:

<template>  
  <div id="app">  
    <v-table  
      row-click-color="#edf7ff"  
      :select-all="selectAll"  
      :select-change="selectChange"  
      :select-group-change="selectGroupChange"  
      :width="1000"  
      :columns="columns"  
      :table-data="tableData"  
      :show-vertical-border="false"  
    ></v-table>  
  </div>  
</template>

<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      tableData: [  
        {  
          firstName: "Jane",  
          lastName: "Smith",  
          phone: "555-555-1212"  
        },  
        {  
          firstName: "Joe",  
          lastName: "Smith",  
          phone: "182-100-1538"  
        },  
        {  
          firstName: "Mary",  
          lastName: "Smith",  
          phone: "161-493-0097"  
        }  
      ],  
      columns: [  
        {  
          width: 60,  
          titleAlign: "center",  
          columnAlign: "center",  
          type: "selection"  
        },  
        {  
          field: "firstName",  
          title: "First Name",  
          width: 100,  
          titleAlign: "left",  
          columnAlign: "left"  
        },  
        {  
          field: "lastName",  
          title: "Last Name",  
          width: 260,  
          titleAlign: "left",  
          columnAlign: "left"  
        },  
        {  
          field: "phone",  
          title: "Phone",  
          width: 330,  
          titleAlign: "left",  
          columnAlign: "left"  
        }  
      ]  
    };  
  },  
  methods: {  
    selectAll(selection) {  
      console.log("select-all", selection);  
    }, 

    selectChange(selection, rowData) {  
      console.log("select-change", selection, rowData);  
    }, 

    selectGroupChange(selection) {  
      console.log("select-group-change", selection);  
    }  
  }  
};  
</script>

We add some extra props and:

{  
  width: 60,  
  titleAlign: "center",  
  columnAlign: "center",  
  type: "selection"  
}

to the columns array.

We can also add pagination with the v-paginator component.

Conclusion

There’re Vue libraries to add data grid to our app in different ways. The vue-js-grid component lets us add a grid with items that can be dragged and dropped.

The vue-easytable component lets us add a table that can have pagination, sorting and many more options available.

Categories
JavaScript Vue

Vue Tips — Making Components Play Nice with Each Other

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at how Vue components can play nice with each other.

Assign Attributes to the Right Elements

We can pass attributes from a grandparent component to a grandchild component by setting the inheritAttrs option to false , and then add v-bind='$attrs' to the child of the grandparent to pass the attributes of the grandparent to the grandchild.

For instance, we can write the following code to do that:

index.js :

Vue.component("foo", {  
  inheritAttrs: false,  
  template: `    
    <p v-bind='$attrs'>foo</p>    
  `  
});

new Vue({  
  el: "#app"  
});

index.html :

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <title>App</title>  
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>  
  </head>  
  <body>  
    <div id="app">  
      <foo class="foo"></foo>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

Then the foo class will be applied to the p element in foo since we set inheritAttrs to false in foo .

Use Browser Norms for Keyboard Navigation

We should follow the conventions for keyboard shortcuts for common operations if we’re going to handle keyboard shortcuts.

For instance, the tab key lets us move to different form fields. Enter is for submitting data, etc.

Use Events Over Callbacks

Emitting events from child to parent is better than callback functions that are passed in from parent to child.

For instance, we have to pass callbacks as props the following way:

index.js :

Vue.component("foo", {  
  props: ["showAlert"],  
  methods: {  
    displayAlert() {  
      if (typeof this.showAlert === "function") {  
        this.showAlert("foo");  
      }  
    }  
  },  
  template: `    
    <button @click='displayAlert'>Click Me</button>  
  `  
});

new Vue({  
  el: "#app",  
  methods: {  
    showAlert(text) {  
      alert(text);  
    }  
  }  
});

index.html :

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <title>App</title>  
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>  
  </head>  
  <body>  
    <div id="app">  
      <foo :show-alert="showAlert"></foo>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

In the code above, we have the show-alert prop, which we pass the showAlert method from the root instance to the child. This is more complex and error-prone because we have to make sure that we passed in a function as the value of the prop.

We have to check that by using typeof of Vue’s built-in prop type validation.

Then we have to call the function that’s passed in as the value of the prop as we did in the displayAlert function. The name is different so it won’t clash with the showAlert prop.

On the other hand, if we emit events, then we won’t have to pass functions from parent to child to run something in the parent when something happens in the child.

For example, we can rewrite the example above by writing:

index.js :

Vue.component("foo", {  
  template: `    
    <button @click='$emit("button-clicked", "foo")'>Click Me</button>  
  `  
});

new Vue({  
  el: "#app",  
  methods: {  
    showAlert(text) {  
      alert(text);  
    }  
  }  
});

index.html :

<!DOCTYPE html>  
<html lang="en">  
  <head>  
    <title>App</title>  
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>  
  </head>  
  <body>  
    <div id="app">  
      <foo @button-clicked="showAlert($event)"></foo>  
    </div>  
    <script src="index.js"></script>  
  </body>  
</html>

The code above is a lot simpler. We just call $emit with the event name as the first argument and the payload that we want to send to the parent as the second.

Then we can listen to the button-clicked event from the parent as we did in index.html by writing:

@button-clicked="showAlert($event)"

Then $event object has the payload, which is 'foo’, so we can pass it straight into the showAlert method. Finally, we’ll see the alert display when we click the button.

Limit In-Component Styles

Scoped in-component styles in single-file components are only applied to the component itself. If we’re reusing it in many locations or apps, then we should let the styles be in that app instead so that we won’t have conflicts of styles between our component and the styles that’s already in the app.

This makes styling reusable components hard since we’ve to deal with conflicts.

Therefore, we should either leave the styles out of the single-file component or have the ability to toggle them on and off.

For instance, we can toggle the styles with an is-styled prop as follows:

HelloWorld.vue :

<template>  
  <div>  
    <p :class="{'is-styled': isStyled}">{{ msg }}</p>  
  </div>  
</template>

<script>  
export default {  
  name: "HelloWorld",  
  props: {  
    msg: String,  
    isStyled: Boolean  
  }  
};  
</script>

<style scoped>  
.is-styled {  
  color: #42b983;  
}  
</style>

App.vue :

<template>  
  <div id="app">  
    <button @click="isStyled = !isStyled">Toggle Style</button>  
    <HelloWorld msg="Hello Vue" :is-styled="isStyled"/>  
  </div>  
</template>

<script>  
import HelloWorld from "./components/HelloWorld";

export default {  
  name: "App",  
  components: {  
    HelloWorld  
  },  
  data() {  
    return {  
      isStyled: true  
    };  
  }  
};  
</script>

In the code above, we have :class to bind the class dynamically according to the value of the isStyled prop that we passed in in HelloWorld.vue

Then in App.vue , we can set the isStyled value and pass it into the is-styled prop as the value so that we can have the ability to turn our HelloWorld ‘s component’s styles on and off as we wish.

Conclusion

We can use v-bind='$attrs' to inherit attributes from parent to child. If we’re going to add keyboard shortcuts handling to our app, we should following the conventions of other apps to make using our app convenient.

Also, we should emit events instead of calling callbacks passed from parent to child.

Finally, if we have shared components, we should either leave out the styles or have the ability to toggle them on and off.

Categories
JavaScript Vue

More Vue Data Grid Components that are Easy to Use

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In this article, we’ll look at some Vue data grid libraries so we can avoid creating them from scratch ourselves.

vue-floatThead

vue-floatThead is a library that lets us create tables with a few options.

We can install it as follows:

npm install vue-floatthead

Then we can use it as follows:

main.js :

import Vue from "vue";  
import App from "./App.vue";  
import FloatThead from "vue-floatthead";  
Vue.use(FloatThead);  
Vue.config.productionTip = false;new Vue({  
  render: h => h(App)  
}).$mount("#app");

App.vue :

<template>  
  <div id="app">  
    <float-thead-table>  
      <thead>  
        <tr>  
          <th>  
            <a href="#">First Name</a>  
          </th>  
          <th>  
            <a href="#">Last Name</a>  
          </th>  
        </tr>  
      </thead>  
      <tbody>  
        <tr v-for='p of persons' :key='p'>  
          <td>{{p.firstName}}</td>  
          <td>{{p.lastName}}</td>           
        </tr>  
      </tbody>  
    </float-thead-table>  
  </div>  
</template>

<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      persons: [  
        { firstName: "Jane", lastName: "Smith" },  
        { firstName: "Alex", lastName: "Smith" }  
      ]  
    };  
  }  
};  
</script>

We registered the component in main.js , then we use the float-thead-table component to build the table.

vue-good-table

vue-good-table is a table library with lots of options. It’s also easy to make a table with filtering and sorting with it.

To install it, we run:

npm install --save vue-good-table

Then to use it, we write:

main.js :

import Vue from "vue";  
import App from "./App.vue";  
import VueGoodTablePlugin from "vue-good-table";  
import "vue-good-table/dist/vue-good-table.css";

Vue.use(VueGoodTablePlugin);  
Vue.config.productionTip = false;

new Vue({  
  render: h => h(App)  
}).$mount("#app");

App.vue :

<template>  
  <div id="app">  
    <input type="text" v-model="searchTerm">  
    <vue-good-table  
      :columns="columns"  
      :rows="rows"  
      :search-options="{  
        enabled: true,  
        externalQuery: searchTerm  
      }"  
    ></vue-good-table>  
  </div>  
</template>

<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      searchTerm: "",  
      columns: [  
        {  
          label: "Name",  
          field: "name",  
          filterable: true  
        }  
      ],  
      rows: [{ name: "Jane" }, { name: "Alex" }]  
    };  
  },  
  methods: {  
    search() {}  
  }  
};  
</script>

We registered the component with Vue.use and imported the styles, then we created the rows and columns data which are passed straight into the vue-good-table as props.

Also, we added the search-options prop to let us pass in the value of the input as the search value. It’s smart enough to search all columns without adding additional code.

Adding pagination is also very easy. To do this, we write:

<template>  
  <div id="app">  
    <input type="text" v-model="searchTerm">  
    <vue-good-table  
      :columns="columns"  
      :rows="rows"  
      :search-options="{  
        enabled: true,  
        externalQuery: searchTerm  
      }"  
      :pagination-options="{  
        enabled: true,  
        mode: 'records',  
        perPage: 5,  
        position: 'top',  
        perPageDropdown: [3, 7, 9],  
        dropdownAllowAll: false,  
        setCurrentPage: 2,  
        nextLabel: 'next',  
        prevLabel: 'prev',  
        rowsPerPageLabel: 'Rows per page',  
        ofLabel: 'of',  
        pageLabel: 'page',   
        allLabel: 'All',  
      }"  
    ></vue-good-table>  
  </div>  
</template><script>  
export default {  
  name: "App",  
  data() {  
    return {  
      searchTerm: "",  
      columns: [  
        {  
          label: "Name",  
          field: "name",  
          filterable: true  
        }  
      ],  
      rows: [  
        { name: "Jane" },  
        { name: "Alex" },  
        { name: "James" },  
        { name: "Joe" },  
        { name: "Bob" },  
        { name: "Mary" }  
      ]  
    };  
  },  
  methods: {  
    search() {}  
  }  
};  
</script>

All we did is pass some pagination options into the pagination-options props. The object we set as the value of the prop includes options for labels, text for the next and previous page buttons, the drop-down for the number of items to display on the table at one time, and more.

It also has a per-column filter feature which we can add easily by changing the column options as follows:

<template>  
  <div id="app">  
    <vue-good-table  
      :columns="columns"  
      :rows="rows"  
      :search-options="{  
        enabled: true,  
        externalQuery: searchTerm  
      }"  
    ></vue-good-table>  
  </div>  
</template>

<script>  
export default {  
  name: "App",  
  data() {  
    return {  
      searchTerm: "",  
      columns: [  
        {  
          label: "Name",  
          field: "name",  
          filterable: true,  
          filterOptions: {  
            enabled: true,  
            placeholder: "Filter Name",  
            filterValue: "",  
            filterDropdownItems: [],  
            filterFn: this.columnFilterFn,  
            trigger: "enter"  
          }  
        }  
      \],  
      rows: \[  
        { name: "Jane" },  
        { name: "Alex" },  
        { name: "James" },  
        { name: "Joe" },  
        { name: "Bob" },  
        { name: "Mary" }  
      ]  
    };  
  },  
  methods: {  
    search() {}  
  }  
};  
</script>

All we added was the follow property to the column entry:

filterOptions: {  
  enabled: true,  
  placeholder: "Filter Name",  
  filterValue: "",  
  filterDropdownItems: [],  
  filterFn: this.columnFilterFn,  
  trigger: "enter"  
}

to enable filtering for the column.

Conclusion

vue-floatThead is a basic table component to let us build a table. On the other hand, vue-good-table is a full-featured table component that has sorting, filtering, pagination right out of the box. It’s also very easy to add those features to our tables.

Categories
JavaScript Vue

Introduction to Vue.js Routing

Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.

In order to create a single-page app with Vue.js, we have to map URLs to components so that when users go to a URL, it’ll show the corresponding component.

In this article, we’ll look at how to create some simple routes with the Vue Router.

Getting Started

We can use by Vue Router by adding a script tag with the URL for the Vue Router library.

We can make a simple app as follows:

src/index.js :

const Foo = { template: "<div>foo</div>" };  
const Bar = { template: "<div>bar</div>" };

const routes = [  
  { path: "/foo", component: Foo },  
  { path: "/bar", component: Bar }  
];

const router = new VueRouter({  
  routes  
});

new Vue({  
  el: "#app",  
  router  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>  
  </head>  
  <body>  
    <div id="app">  
      <div>  
        <router-link to="/foo">Foo</router-link>  
        <router-link to="/bar">Bar</router-link>  
      </div>  
      <router-view></router-view>  
    </div>  
    <script src="src/index.js"></script>  
  </body>  
</html>

In the code above, we defined 2 components Foo and Bar in src/index.js .

Then we mapped them to routes with:

const routes = [  
  { path: "/foo", component: Foo },  
  { path: "/bar", component: Bar }  
];

const router = new VueRouter({  
  routes  
});

Then we created a new Vue instance with:

new Vue({  
  el: "#app",  
  router  
});

In the template, we have router-links to map the routes to a tags with the URLs to correspond to the routes we define:

<router-link to="/foo">Foo</router-link>  
<router-link to="/bar">Bar</router-link>

Then we have router-view to show the components that are mapped to routes:

<router-view></router-view>

In the end, we should get:

Foo Link Bar Linkfoo

when we click on Foo Link .

and:

Foo Link Bar Linkbar

when we click on Bar Link .

Once we injected the router, we also get access to this.$router .

We can use it to navigate between routes. For example, we can write the following:

src/index.js :

const Foo = { template: "<div>foo</div>" };  
const Bar = { template: "<div>bar</div>" };

const routes = [  
  { path: "/foo", component: Foo },  
  { path: "/bar", component: Bar }  
];

const router = new VueRouter({  
  routes  
});

new Vue({  
  el: "#app",  
  router,  
  methods: {  
    goBack() {  
      window.history.length > 1 ? this.$router.go(-1) : this.$router.push("/");  
    }  
  }  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>  
  </head>  
  <body>  
    <div id="app">  
      <div>  
        <router-link to="/foo">Foo Link</router-link>  
        <router-link to="/bar">Bar Link</router-link>  
        <a href="#" @click="goBack">Go Back</a>  
      </div>  
      <router-view></router-view>  
    </div>  
    <script src="src/index.js"></script>  
  </body>  
</html>

Then when we click the Foo Link and Bar Link links a few times then click Go Back , we’ll see it’ll go back to the previous routes that we navigated to.

Route Parameters

We can get route parameters with the this.$route.params object.

For example, we can write an app that shows the URL parameter that’s passed in as follows:

src/index.js :

const User = {  
  computed: {  
    username() {  
      return this.$route.params.username;  
    }  
  },  
  template: `<div>{{username}}</div>`  
};

const routes = [{ path: "/user/:username", component: User }];

const router = new VueRouter({  
  routes  
});

new Vue({  
  el: "#app",  
  router  
});

index.html :

<!DOCTYPE html>  
<html>  
  <head>  
    <title>App</title>  
    <meta charset="UTF-8" />  
    <script src="https://unpkg.com/vue/dist/vue.js"></script>  
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>  
  </head>  
  <body>  
    <div id="app">  
      <div>  
        <router-link to="/user/foo">Foo</router-link>  
        <router-link to="/user/bar">Bar</router-link>  
      </div>  
      <router-view></router-view>  
    </div>  
    <script src="src/index.js"></script>  
  </body>  
</html>

The :username in “/user/:username” is the parameter, so we can get what passed in after /user/ by using this.$route.params.username .

We added a computed property username which returns this.$route.params.username so we can use:

`<div>{{username}}</div>`

to show the username URL parameter.

Conclusion

We can map URLs to components by using Vue Router.

Once we included it, we can define routes which map URLs to components. They can also take parameters, which can be retrieved with the this.$route object that’s made available by injecting the Vue router into our app.

To display links that link to Vue Router routes, we use router-link , and to display the components mapped to routes, we use router-view .