【CV達成27%⤴ 】月間80万人に読まれるオウンドメディア「データのじかん」サイト改善の裏側
 
                    
                わかりやすいようなめちゃくちゃわかりづらいようなタイトル(笑)
①アプリ側(Vue.js)からユーザ情報を外部サーバ(Laravel)になげる 
②Laravel側で、受け取った情報に紐づく追加情報をデータベース(mysql)から抽出し、Jsonデータとしてアプリ側(Vue.js)に投げ返す
③返ってきた追加情報をアプリ側(Vue.js)で表示させる
想定としては、“ログイン情報からユーザ情報を取得し、プロフィール画面に表示する”みたいなことをしようとしてます。
▼ profile.vue
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <script> export default {     data() { //データの初期値を設定       return {         userid: "",         name: "",         profile: "",         sex: "",         birth: "",         pref: "",       };     },     methods: {       getProfiles() {         const data = {           userid: 'bonchan' //今回投げるuserid         }         var self = this;         axios.post('https://Larabel側URL/profile', data)           .then(res =>  {             self.userid = res.data.userid;             self.name = res.data.name;             self.profile = res.data.profile;             self.sex = res.data.sex;             self.birth = res.data.birth;             self.pref = res.data.pref;         }).catch( error => { console.log(error); });       }     },     created() { //APIアクセスでgetProfiles()を呼び出す       this.getProfiles()     }   } </script> | 
とりあえず、固定のuserid「bonchan」を投げたら、ニックネームとか出身地とかひっぱってくる感じにします。通信にはaxiosを使いました。この設定などは別記事で載せます><
▼routes/web.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ //Route::get('/', function () { //    return view('welcome'); //}); Route::post('/profile', 'ProfileController@get_profile'); | 
まず、http://●●/profileにpostリクエストされたらProfileController.phpのget_profile関数を参照させます。
▼Http/Controllers/ProfileController.php
| 1 2 3 4 5 6 7 8 9 10 | public function get_profile(Request $request) {   header("Access-Control-Allow-Origin: *");  //CORS   header("Access-Control-Allow-Headers: Origin, X-Requested-With");   $userid = $request->userid; //postされてきたuseridを変数にいれる   $profiles = Profile::where('userid', '=', $userid) ->get()->toArray(); //profilesテーブルから、useridが一致するデータを抽出   //dd($profiles);   $data = response()->json($profiles[0]); //json形式に   return $data; } | 
DBからデータを抽出し、最後Json形式にしてデータを投げ返します!Json形式について、こちらの記事がめちゃくちゃわかりやすいです。CORS処理記載もありますが、、これも別記事にまとめます><
▼ profile.vueのJS
| 1 2 3 4 5 6 7 8 9 10 |         var self = this;         axios.post('https://Larabel側URL/profile', data)           .then(res =>  {             self.userid = res.data.userid;              self.name = res.data.name;             self.profile = res.data.profile;             self.sex = res.data.sex;             self.birth = res.data.birth;             self.pref = res.data.pref;         }).catch( error => { console.log(error); }); | 
「1.Vue.js側でのPOST処理」で全部書いてありますが、、「res.data.キー名」で返ってきた値を、ひとつづつ代入してます。もっといいやり方はありそう..。
またthis.name = res.data.name;で代入しようとしたところ、thisが本来のデータを参照してくれずうまく値を入れられなかったので、selfにいったん退避させるという方法をとりました。参考はこちら
▼ profile.vueのHTML
| 1 2 3 4 5 6 7 8 9 10 11 12 |       <div class="name">         <dl class=" prof_box">           <dt class="label"><label for="name">ニックネーム</label></dt>           <dd class="input"><input maxlength="50" name="name"    placeholder="ニックネームを追加" class="input_name" v-model="name"></dd>         </dl>       </div>       <div class="profile">         <dl class=" prof_box">           <dt class="label"><label for="profile">プロフィール</label></dt>           <dd class="input"><textarea maxlength="160" name="description" placeholder="プロフィールを追加" class="input_prof" v-model="profile">{{ profile }}</textarea></dd>         </dl>       </div> | 
一部抜粋です。返ってきたデータは{{ profile }}のように二重かぎかっこで表示させることができました。inputのvalueに入れたいときは、v-model=”name”と記述することで、value値に表示させることができました。
ひとまずこれで表示することができました。vue.js、Laravel初心者のため手探りすぎるので、、もっと良いやり方あったら教えていただきたいです!
 
 
                            編集者:コウ
年間20万人が訪れるKOHIMOTO Laboの 広報・編集・AIアシスタント⛄を担当しています。興味→Web・AI・ソーシャル・映画・読書|テクノロジー × ヒューマニティのpositiveな未来🌍
PICK UP