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

フロントVue.js、サーバーサイドLaravelの実装方法

Posted at

概要

1つのアプリを、フロントはVue.js、サーバーサイドはLaravelで作成し、Vue.js側でサーバーサイドをAPIとして引っ張ってきて使用したい。

axios

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

const URL_BASE = '全ページ共通のホスト部分URL';
var token = "生成されたトークン";

//新しいVuexを生成
export default new Vuex.Store({
  state: {
    list: []
  },
  actions: {
    //このcontextがないと、urlが上手く渡って来ないことがある。
    get_ajax(context, url) {
      //変数urlはviewで定義する
      return axios.get(URL_BASE + url, {    
         //このheadersは、認証が必要なページの時に記載する。
          headers: {
            "Content-Type": "application/json",
            "Authorization": 'Bearer ' + token
          },
          responseType: 'json',
        })
        //resに送られてきたデータが入っている。
        .then((res) => {
          //下記の記載で、ここの配列listにres.dataをsetしている。
          Vue.set(this, 'list', res.data);
        });
    },
  }
});
views/index.js
//ここら辺は今回関係ないとこ
<template>
  <div>
    <Template/>
  </div>
</template>


<script>
  //これは今回関係なし。
  import Template from "@/common/Template.vue"
  //vuexのmapActionsが使えるようになる。
  import { mapActions } from 'vuex'

  var url = 'このサーバーサイドで実装した、このviewページのurl';

  export default {
    data() {
      return {
        list: []
      }
    },
    //ここら辺も今回関係なし
    components: {
      Template
    },
    //mapActionsにstoreで定義したget_ajaxが使えるように記載する。
    methods: {
      ...mapActions([
        'get_ajax'
      ]),
    },
    //asyncとawaitで非同期通信となる。
    async mounted() {
      await this.get_ajax(url).then(()=>{
        //ここの記載でdataの中の配列listにstoreで定義されたlistを代入している。
        this.list = this.$store.list;
      });
    }
  }
</script>

参考資料
https://qiita.com/ksh-fthr/items/2daaaf3a15c4c11956e9

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?