Laravel 5.6 + Vue.js で、SPA開発(3) 状態の保持 #Laravel #vue.js #SPA #PHP
index:
概要:
前回のSPA(SinglePageApplication) 構成で、Laravel 5 +vue.js
の関連となります。
複数の画面を遷移した時の、
横断的に変数値を保存する方法について、検討してみました。
会員制サイト等での、ログイン情報等を保存し。
各ページで、保存された変数を使用。
=>今回は、vuex を使用せず。localStorageに保存しています。
環境
php7.1
Laravel 5.6
Vue.js
参考の設定
resource など、一部のフォルダです。
github.com
実装など
ユーザー追加等は、Laravel のauth 機能を
追加しました。(手抜きですが。)
php.exe artisan make:auth
php.exe artisan migrate
下記で、ユーザーを追加しておきます、
http://localhost:8000/register
・app.js
https://github.com/kuc-arc-f/spa1_ver2/blob/master/resources/assets/js/app.js
認証画面を追加
{ path: '/users/login' , component: require('./components/Users/Login.vue') },
・api.php
https://github.com/kuc-arc-f/spa1_ver2/blob/master/routes/api.php
認証API の追加
// users Route::post('users/auth', function(Request $request) { $const = new AppConst; $ret=$const->NG_CODE; $email = request('email'); $password= request('password'); //var_dump( $password ); $query = App\User::query(); $query->where('email', $email); $user = $query->first(); if (Hash::check($password, $user->password)) { $ret= $const->OK_CODE; } return ['ret'=>$ret,'user'=> $user ]; });
Vue.js
・Login.vue
https://github.com/kuc-arc-f/spa1_ver2/blob/master/resources/assets/js/components/Users/Login.vue
ログイン認証が、完了した場合。結果をストレージに保存しています。
<template lang="html"> <div class="container"> <h1>User -Login</h1> <div class="form-group"> <label for="email">email</label> <input type="text" class="form-control" id="email" v-model="email" > </div> <div class="form-group"> <label for="password">password</label> <input type="password" class="form-control" id="password" v-model="password" > </div> <button v-on:click="postLogin">ログイン</button> </div> </template> <script> export default { data() { return { email:'', password:'', store: [], user: [] } }, mounted: function() { }, methods: { postLogin(){ var user = { 'email': this.email, 'password': this.password }; axios.post('/api/users/auth/' ,user).then(res => { console.log(res.data ); if(res.data.ret==1){ this.user = res.data.user this.store.push({ id: this.user.id }) myStorage.save( this.store ) window.location.href='/' }else{ console.log('#-NG-auth'); } }); } } } </script>
・my_storage.js
localStorage 処理
https://github.com/kuc-arc-f/spa1_ver2/blob/master/public/js/my_storage.js
実行結果
・指定ページ、ログアウト後に開くと。
認証状態をチェックして、
ログイン画面に。強制 リダイレクトできました。
(vue-router 経由)
その他
・flashメッセージ表示を追加しました。
(2019/04/15)
・/tasks/new/ で、登録、完了後。
/tasks 、一覧で。完了メッセージを表示。
・Vueコンポーネントは、
resources\assets\js\components\Layouts\FlashMessage.vue
を追加
https://github.com/kuc-arc-f/spa1_ver2/blob/master/resources/assets/js/components/Layouts/FlashMessage.vue