LoginSignup
39
37

More than 5 years have passed since last update.

vuex と vue-router の共存について

Posted at

初学者ゆえなのか、vuex と vue-router を共存させる記述が分からなくて半日費やしてしまったので備忘録。

サンプル

検索していたら見つけたIssueに、色々アドバイスが書いてあった。
https://github.com/vuejs/vuex/issues/11

ここの内容を基にサンプルを作成してみた。ルーティングは route-config.js として別ファイルに定義するようにしてみた。

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>SAMPLE APP</title>
  </head>
  <body>

    <div id="app"></div>

  </body>
</html>
main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'
import { configRouter } from './route-config'

Vue.use(VueRouter)

const router = new VueRouter({
  history: true,
  saveScrollPosition: true
})

configRouter(router)

router.start(App, '#app')
App.vue
<template>
  <div>
    <a v-link="{ path: '/post' }">Go to Post</a>
    <router-view></router-view>
  </div>
</template>

<script>
  import store from './vuex/store'
  export default {
    name: 'App',
    store: store
  }
</script>
route-config.js
import Post from './components/Post'

export function configRouter (router) {
  router.map({
    '/post': {
      component: Post
    }
  })
}

vuex-router-sync

さっきのIssueページの中のコメントにも書いてあるけど、簡単にvuexとvue-routerを使えるようにしてくれるこんな物もあるみたい。後で試す。
https://github.com/vuejs/vuex-router-sync

vuex-router-syncのボイラープレートを書いてくれている人がいるので、サンプルを見てみると使い方が良く分かると思う。
https://github.com/funkyLover/vue-boilerplate

39
37
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
39
37