Vue.js vue-routerの簡単なサンプルコード
- 作成日 2019.12.07
- Vue.js
- vue-router, Vue.js

vue-routerでページ遷移を実現する簡単なサンプルコードです。
環境
- OS ubuntu19.10
- node v12.13.0
- npm 6.12.1
※ubuntu19.10にnodeのインストールはこちら
プロジェクト作成
r-testという名前でプロジェクトを作成します
vue init webpack r-test
? Install vue-router? Yesとし vue-router を利用します。
? Project name r-test
? Project description A Vue.js project
? Author
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Set up unit tests No
? Setup e2e tests with Nightwatch? No
? Should we run `npm install` for you after the project has been created? (recommended) yarn
router利用
routerを利用して/testページに遷移させてみる
src/component内にTest.vueを作成します
<template>
<div class="test">
<h1>{{ msg }}</h1>
<router-link to="/">Home</router-link>
<router-link to="/test">testページ</router-link>
</div>
</template>
<script>
export default {
name: 'test',
data () {
return {
msg: 'テストページです'
}
}
}
</script>
<style scoped>
h1 {
margin: 40px 0 0;
color: #41B883;
}
a {
color: #41B883;
}
</style>
src/router内のindex.jsを下記の通りに編集します
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
//追加
import Test from '@/components/Test'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
//追加
{
path: '/Test',
name: 'テスト',
component: Test
}
]
})
src/component内のHelloWorld.vueもtestページにリンクできるように、htmlを少し修正します
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>Essential Links</h2>
<router-link to="/">Home</router-link>
<router-link to="/test">testページ</router-link>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Vue.js vue-routerの簡単なサンプルコード'
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
起動して確認してみる。
npm run dev
ブラウザよりhttp://localhost:8080にアクセスすると下記の画面が表示される

testページへのリンクをクリックすると
http://localhost:8080/#/testにリンクします。

-
前の記事
Windows10 ProにDocker for Windowsをインストールする 2019.12.07
-
次の記事
Nuxt.js Client bundleが進行しない時の対処法 2019.12.08
コメントを書く