Help us understand the problem. What is going on with this article?

Vue-routerで遷移時にパラメタを渡し方

More than 1 year has passed since last update.

vue-routerで画面遷移時にパラメータ渡すのに手詰まったのでメモ

サンプルリポジトリ

https://github.com/Godan/tutorial-vue-router

サンプルのvue-routerのルーティング

pathにはパターンを書きます。:を先頭に書くのはrailsのroutesと同様ですね。

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'index-page',
      component: require('@/components/index').default
    },
    {
      path: '*',
      redirect: '/'
    },
    {
      path: 'fuga',
      name: 'fuga-view',
      component: require('@/components/fuga').default
    },
    {
      path: '/hoge/:value',
      name: 'hoge-view',
      component: require('@/components/hoge').default
    }
  ]
})

リンク元ページ

リンク元でrouter-linkタグを使ってリンクを張ります。toの中身はハッシュで渡していきます。

<template>
  <div id="wrapper">
        <router-link :to="{ name: 'hoge-view', params: { value: 'test value' }}" >hoge Link</router-link >
        <router-link :to="{ name: 'fuga-view' }" >fuga Link</router-link >
    </main>
  </div>
</template>

リンク先ページ

リンク先は通常変数と同様に展開します。

<template>
  <div>
    <router-link :to="{ name: 'index-page' }"> back </router-link>
    This is hoge page.   value is {{ $route.params.value }} 
  </div>
</template>

リンクが変更されたときに関数を呼び出す

変更に合わせて関数を呼び出す場合はvueに用意されているウォッチャーを使います

new Vue({
  components: { App },
  router,
  store,
  template: '<App/>',
  watch: {
    $route: function (to, from) {
      // ここにコードを書く
    }
  }
}).$mount('#app')

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした