LoginSignup
27
23

More than 5 years have passed since last update.

vue-routerでパラメータ付きルートを設定する方法 in Laravel

Posted at

■ルートの定義

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

以上。

27
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
23