8
8

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 5 years have passed since last update.

Vue.jsで記事詳細のデータを取得

Last updated at Posted at 2018-11-10

Vue.jsで記事詳細ページのURLを記事IDに設定して、その記事のdataを展開していくときの書き方です。

routerを設定

vue-router」をinstall

$ yarn add vue-router

vue-routerをインスタンスにして#appに読み込む。

main.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App';
import routes from './routes';

Vue.use(VueRouter);

const router = new VueRouter(routes);

new Vue({
  el: '#app',
  components: { App },
  template: '<App/>',
  router,
});
routes.js
import Articles from './page/Articles';
import Detail from './page/Detail';

export default {
  mode: 'history',
  routes: [
    {
      path: '/articles',
      component: Articles,
      name: 'articles',
    },
    {
      path: '/articles/:id',
      component: Detail,
      name: 'detail',
    },
  ],
};

記事詳細ページにその記事のデータを取得

記事一覧で記事をClickして詳細ページに遷移したときに、その記事のデータをURLの「:id」を元に取得します。
まずは記事一覧で記事詳細の遷移先を/articles/:idにしました。

ArticleItem.vue
<template>
  <ul>
    <li v-for="(article, index) in articles" :key="index">
      <a :href="'/articles/' + article.id">
        {{article.text}}
      </a>
    </li>
  </ul>
</template>

<script>
export default {
  computed: {
    articles() {
      return this.$store.state.articles; // storeから記事データを取得
    },
  },
};
</script>

詳細ページに遷移してURLが/articles/:idになったとき、this.$route.params.idでその「:id(記事id)」を取得できます。
そこで、storeのdataからそのidと一致するdataを抽出してcomponentのpropsに渡しています。

Detail.vue
<template>
  <div>
    <article-detail
      :data="ArticleData"
    >
    </article-detail>
  </div>
</template>

<script>
import ArticleDetail from '../components/ArticleDetail';

export default {
  computed: {
    ArticleData() {
      const dataId = parseInt(this.$route.params.id, 10);
      const data = this.$store.state.articles.find(a => (
        a.id === dataId
      ));
      return data;
    },
  },
  components: {
    articleDetail,
  },
};
</script>
ArticleDetail.vue
<template>
  <div>
    <p>{{data.title}}</p>
    <p>{{data.text}}</p>
  </div>
</template>

<script>
export default {
  props: {
    data: Object,
  },
};
</script>

こんな感じで合っっていますでしょうか?

参考サイト

8
8
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
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?