■ルートの定義
JSファイルでvueやvue-routerのimport等色々やる
// resources/assets/js/app.js
// vueとvue-routerのインポート
import Vue from 'vue'
import VueRouter from 'vue-router'
// VueRouterを使いますという宣言
Vue.use(VueRouter);
// vue-routerのインスタンス生成 ここでパスを設定する
const router = new VueRouter({
mode: 'history',
routes: [
// パラメータ付きの場合はコロンを使ってパラメータを表現する
{ path: '/articles/:id', component: require('./components/Articles/Show.vue') },
]
});
■Componentでパラメータを使う
コンポーネント側ではthis.$route.params
でパラメータを受け取れる。
今回パラメータはidのみなのでthis.$route.params.id
で取得可能。
//Show.vue
<template>
<div>
<div>
<h2>{{article.title}}</h2>
<p>
{{ article.content }}
</p>
</div>
</div>
</template>
<script>
export default {
// メソッドの実行
created() {
this.getArticle()
},
// メソッド&テンプレート内で使う変数を定義
data() {
return {
article: ''
}
},
// (読み込み時に)実行するメソッド
methods: {
getArticle() {
// this.$route.params.idをaxiosで非同期接続するパスのパラメータに設定している
axios.get('/api/article/' + this.$route.params.id).then(res => {
this.article = res.data
});
}
}
}
</script>
こちらのリファンレスを参照しました。
https://router.vuejs.org/ja/essentials/dynamic-matching.html
以上。