> For the complete documentation index, see [llms.txt](https://super-yusuke.gitbook.io/udemy-vue-basic/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://super-yusuke.gitbook.io/udemy-vue-basic/untitled-2.md).

# View-router

インストール。通常 module システムの中で使うことになると思うので、use で宣言してから使用すること。

{% code title="router/index.js etc..." %}

```javascript
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
```

{% endcode %}

routing を設定する。

{% code title="router/index.js etc..." %}

```javascript
const routes = [
  {
    path: '/',
    name: 'Login',
    component: Login
  },
  {
    path: '/nologin',
    name: 'Nologin',
    component: NoLogin
  },
  {
    path: '/index',
    name: 'Index',
    component: Index,
  }
]

// name をつけておくと、
// this.$router.push({name: 'route-name'}) で移動できて便利
```

{% endcode %}

{% code title="router/index.js etc..." %}

```javascript
const router = new Router({
  routes: routes
})

// 以下でもいい
const router = new Router({
  routes
})
```

{% endcode %}

module を出力する。

{% code title="router/index.js etc..." %}

```javascript
export default router
```

{% endcode %}

router を注入

{% code title="main.js ...etc" %}

```javascript
import Vue from 'vue'
import App from './App'
import router from './router'

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router, // router をかます
  components: { App },
  template: '<App/>'
})

```

{% endcode %}

注入して入れば、router-view コンポーネントして自動的に使える模様。

{% code title="app.vue ...etc" %}

```javascript
<template>
  <div>
    <router-view/>
  </div>
</template>
```

{% endcode %}

{% code title="etc.vue" %}

```javascript
export default {
  computed: {
    username () {
      // 多分これで url のクエリのうち username が取れる
      return this.$route.params.username
    }
  },
  methods: {
    goBack () {
      // this.$router で history オブジェクトの操作にも
      window.history.length > 1
        ? this.$router.go(-1)
        : this.$router.push('/')
    }
  }
}

```

{% endcode %}
