こんにちは、みっきーです。
現在Laravel+Vue.jsで開発をしています。
当初簡単な処理を使い回すのにVue.jsを使用していたのですが、開発が進むにつれ複雑化するわ肥大化するわで全私がもやもやする状態になりました。
そこで今回はこのもやもやを改善してVue.jsを使い倒す方法を考えたので備忘として残します。
Vue.jsでごりごりしたい方はお付き合いください。
Laravel 5.4
Vue.js 2.x
*他ライブラリの話はしません
Vue.js実行までの流れ
- Laravelのconfigに出力したいJSファイル名の一覧を設定
- ページごとに引数を使ってBladeにパラメータ出力
- base.jsでパラメータを元に各Vueを出力
Laravelのconfigに出力したいJSファイル名の一覧を設定
<?php return [ // ページ名とかURLとか一意のもの => JSファイル名 'hoge' => 'hoge' 'hogehoge' => 'hoge' 'piyo' => 'piyo' ];
ページごとに引数を使ってBladeにパラメータ出力
<!DOCTYPE html> <html lang="ja"> <head> @include("head") </head> <body> <div id="app"> @include("header") @yield("contents") @include("footer") </div> <!-- JS読み込み --> <script id="js-file-name" src="js/base.js" data-pageInfo={{ $JSFileName }}></script> </body> </html>
base.jsでパラメータを元に各Vueを出力
import * as Vue from 'vue'; // 読み込むJS名取得 var pageInfo = document.getElementById('js-file-name').dataset.pageinfo; var jsonPageInfo = JSON.parse(pageInfo); // ファイル名以外に受け取りたいデータを登録 import store from './store'; store.setStoreData('hoge', jsonPageInfo.hoge); // ファイル読み込み if (jsonPageInfo.jsFileName !== undefined) { require(jsonPageInfo.name + '.js'); }
Vue.jsの構造
- 複数ファイルで使用したい処理はcommon.jsを作ってライブラリ化
- 複数回使い回す機能はcomponentで対応
- 共有したいデータはstore.jsを作成し一元管理
複数ファイルで使用したい処理はcommon.jsを作ってライブラリ化
common.js
export default { hogehoge: function (key, value) { // 処理 }, }
default.js
// ライブラリ読み込み import Common from '../common'; let app = new Vue({ el: '#app', methods: { hogehoge(key, value) { Common.hogehoge(key, value); }, } });
複数回使い回す機能はcomponentで対応
default.js
// コンポーネント読み込み import hoge from '../components/hoge'; import hogehoge from '../components/hogehoge'; let app = new Vue({ el: '#app', components: { hoge, hogehoge, }, });
共有したいデータはstore.jsを作成し一元管理
store.js
export default { state: { debug: false; hoge: hoge; }, setStoreData(key, newValue) { if (this.state.debug) console.log('setMessageAction', key, newValue); this.state[key] = newValue; }, getStoreData(key = null) { if (key === null) console.log(this.state); if (this.state.debug) console.log('getMessageAction', key, this.state[key]); return this.state[key]; } }
default.js
// ストア読み込み import store from '../store'; let app = new Vue({ el: '#app', data: function () { return { state: store.state } }, methods: { setStoreData(key, newValue) { store.setStoreData(key, newValue); }, getStoreData(key) { store.getStoreData(key); }, } });
考えてみた感想
ファイルの複雑化と肥大化の解消、データの切り分け、処理の共通化、出力ファイルはPHP側で制御できるようになりました。
ずいぶんうまく使える状態になったのですが、ものたりない感じがします。
bladeからパラメータを渡してJSでファイルを読み込む方法はもっとスマートにできないかなって思いました。
一緒に考えてくれる方を大募集中です!
ご意見ご感想お待ちしてます!!
以上備忘録でした。ヾ(。・ω・。)ばいばーい
弊社では楽しく真剣にプロダクトと向き合い、『明日のはたらくを創る』仲間を募集中です!
https://919.jp/recruit/mid-market/