1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Vue.js Rails ページ遷移

Last updated at Posted at 2020-07-20

#前提
Rails 5.2
Ruby 2.5.1

package.json
{
  "name": "app",
  "private": true,
  "dependencies": {
    "@rails/webpacker": "5.1.1",
    "vue": "^2.6.11",
    "vue-loader": "^15.9.3",
    "vue-template-compiler": "^2.6.11"
  },
  "devDependencies": {
    "webpack-dev-server": "^3.11.0"
  }
}

ファイル構成

app
|--javascript
   |--packs
      |--hello_vue.js
   |--app.vue

#本題
かなり初歩的ですが、とても躓いたため記述しました。

・VueRouterを導入

$ npm install vue-router

・app.vueにを追記

app.vue
<template>
  <div id="app">
    <!-- 追記 -->
    <RouterView />
    <p>{{ message }}</p>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      message: "Hello Vue!",
    };
  }
};
</script>

・app/javascript/packsの中にpagesフォルダー作成
・作成したpagesフォルダーのなかに、ファイルを2つ作成。

pages/Hoge.vue
<template>
  <div>
    <router-link to="/">Test</router-link>
  </div>
</template>
pages/test.vue
<template>
  <div>
    <router-link to="/hoge">Hoge</router-link>
    <p>login</p>
  </div>
</template>

・packsフォルダーにrouter.jsを作成

router.js
import Vue from "vue";
import VueRouter from "vue-router";

import Test from "./pages/Test.vue";
import Hoge from "./pages/Hoge.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    component: Test,
  },
  {
    path: "/Hoge",
    component: Hoge,
  },
];

const router = new VueRouter({
  mode: "history",
  routes,
});

export default router;

・hello_vue.jsにvue-routerを追記

hello_vue.js
import Vue from "vue";
import router from "./router";
import App from "../app.vue";

document.addEventListener("DOMContentLoaded", () => {
  const app = new Vue({
    router,
    components: { App },
    template: "<App />",
    render: (h) => h(App),
  }).$mount();
  document.body.appendChild(app.$el);
});

ビルド後にページリロードして動作確認。

# bin/webpack-dev-server
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?