Skip to content

Commit

Permalink
第三回 APIを使用して動的なSPAを作成する
Browse files Browse the repository at this point in the history
  • Loading branch information
EC2 Default User committed Jul 28, 2019
1 parent f353aeb commit bbbe8d1
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 6 deletions.
18 changes: 18 additions & 0 deletions src/api/products.js
@@ -0,0 +1,18 @@
//商品のリスト
const database = [
{id:1, name:'商品A', price:345, content:'商品Aの紹介です'},
{id:2, name:'商品B', price:9876, content:'商品Bの紹介です'},
{id:3, name:'商品C', price:123, content:'商品Cの紹介です'},
]
//インポート先で使用できる関数をオブジェクトとしてまとめたもの
export default {
// databaseを取得
fetch(id) { return database },
// idパラメーターに従ってdatabaseからdataを抽出
find(id) { return database.find(el => el.id === id) },
anyncFind(id, callback) {
setTimeout(() => {
callback(database.find(el => el.id === id))
}, 1000)
}
}
8 changes: 6 additions & 2 deletions src/router.js
Expand Up @@ -16,8 +16,12 @@ const router = new VueRouter({
routes: [
{ path: '/', component: Home},
{ path: '/product', component: ProductList},
// { path: '/product/:id', component: Product}, :idとしておけばパラメータに可変の値を入れられる
{ path: '/product/:id(\\d+)', component: Product}, //(\\d+)を付ければパラメータには数字しか入らない正規表現となる


{ path: '/product/:id(\\d+)',
component: Product,
// propsにidとデータ型の指定をする
props: route => ({ id: Number(route.params.id) })},
]
})

Expand Down
10 changes: 8 additions & 2 deletions src/views/Product.vue
Expand Up @@ -3,6 +3,12 @@
<h1>商品情報</h1>
<!--$routeは現在のrouteインスタンスを表す-->
<!--:idでパラメーターを指定したものは、params.idで呼び出せる-->
<p>このページは、ID.{{ $route.params.id }}の詳細を表示する</p>
<p>このページは、ID.{{ id }}の詳細を表示する</p>
</div>
</template>
</template>

<script>
export default {
props: { id: Number }
}
</script>
20 changes: 18 additions & 2 deletions src/views/ProductList.vue
@@ -1,5 +1,21 @@
<template>
<div class="product">
<div class="product-list">
<h1>商品一覧</h1>
<ul>
<!--受け取ったdatabaseをv-forでリストレンダリング-->
<li v-for="{id,name} in list" :key="id">
<router-link :to="`/product/${ id }`">{{ name }}</router-link>
</li>
</ul>
</div>
</template>
</template>

<script>
import products from '@/api/products.js'
export default {
computed: {
// products.jsから引き受けたdatabaseをlistという変数にして受け取る
list: () => products.fetch()
}
}
</script>

0 comments on commit bbbe8d1

Please sign in to comment.