はじめに
こんにちは!
株式会社イメージ・マジックの技術ブログ、今回担当の宮川です。
本ブログでは、イメージ・マジックがどんな技術を扱っているのかを知ってもらうために、業務で得た知識のまとめやハマって解決したこと、技術選定理由、最新技術動向などや、社内の雰囲気が伝わる内容を書いていきたいと思います。
今回は、社内のプロジェクトで採用している、Vue.jsについて書きます。

2018/03月入社、前職SIer、現在はPHPとフロントエンド開発しています。
Symfony、Elastic SearchとVue.jsに関心があります。趣味は山登りです。
Vue.js所感
Vue.js使い始めて2カ月ですが、所感として良いところは概ね以下かなと思ってます。
- データバインディングが簡潔
- 部品化しやすい
- 機能の分類が細やかで配慮が行き届いている
- だいたいライフサイクルがいい感じにやってくれる
Vue.js ハマったところ
以下、まとめました。
1. Arrayの更新は、以下の方法で更新しないとVue.jsが検知してくれない
1 2 3 4 5 | // Vue.set Vue.set(vm.items, indexOfItem, newValue) // Array.prototype.splice vm.items.splice(indexOfItem, 1, newValue) |
2. DOMレンダリングが完了したタイミングで処理したい
1 2 3 | Vue.nextTick( function () { //処理 }) |
3. 親子間のデータの受け渡し
1 2 3 4 5 6 7 | // 親はプロパティを渡す <children customprop= "parent.child" ></children> // 子はcustompropを受け取る Vue.component( 'my-component' , { template: `<input type= "text" value= "customprop" >` }) |
4. 「input type=”file”」は、値をbindできない
01 02 03 04 05 06 07 08 09 10 11 12 | // NG v-modelでbindできない <input type= "file" v-model= "property.file" /> // ファイルを取得する場合は、onChangeでイベントを受け取る <input type= "file" @onChange= "storeFile($event)" /> // js ... storeFile: function (event) { const file = event.target.files[0] }, ... |
5. $.emit()には、キャメルケースは使用できない
1 2 3 4 5 | // NG(キャメルケースは不可) $.emit( 'updateParent' ) // OK(チェインケース(ハイフン区切り)は可。) $.emit( 'update-parent' ) |
6. Vue.jsのtemplateの最上位タグには v-forは使用不可
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // NG Vue.component( 'my-component' , { template: ` <li v- for = "item in items" > {{ item.message }} </li> ` }) // OK // 最上位タグの子タグで、v-forを使用する。 Vue.component( 'my-component' , { template: ` <ul> <li v- for = "item in items" > {{ item.message }} </li> </ul> ` }) |
7. webpackで複数のjsファイルでそれぞれ定義したVueが読み込めない
webpackで分割すると、Vue自体のインスタンスが異なるためイベントが発生できない。importすれば問題無く動作する。
1 2 3 4 | import {EventBus} from '../Util/EventBus' ; import AutoCompleteInput from '../AutoCompleteInput.vue' ; import AutoCompleteList from '../AutoCompleteList.vue' ; ... |
8. Webpackで単一ファイルコンポーネントをcompileすると、cssがjs以下に出力
1 2 | × public/js/... ○ public/css/... |
9. Vue.jsの初期化後に、動的に追加したhtmlにVue.jsは適用できない
図のInitでEventsのAttach等行うため