VueJS開発で知っていると役立つ情報をまとめます。
<目次>
Visual Studio Codeの設定
Veturをインストール
Vetureを入れるとVueJSの開発が楽になります。
settings.jsonの設定
以下の設定を入れるとコードの整形が楽になります。
1 2 |
"vetur.format.defaultFormatter.html": "js-beautify-html", "editor.formatOnSave": true |
settings.jsonは、Macをお使いの場合には、「command + ,」で設定ウィンドウを開き、検索欄に「json」と打ち込むと探せると思います。
インポート
@を使用する
@は、srcディレクトリを指すので、以下のようにモジュールをインポートできます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# ディレクトリ構造 src/ ├── App.vue ├── assets │ └── logo.png ├── components │ └── TodoList.vue ├── main.js # App.vueからTodoList.vueをインポートする場合 import TodoList from '@/components/TodoList.vue'; == import TodoList from './components/TodoList.vue'; |
モジュールのインストール
Sassを導入
Sassを導入します。
モジュールのインストール
1 |
npm install --save-dev sass-loader node-sass |
1 2 3 |
<style lang="scss"> </style> |
Webpack設定
Webpackに設定を追加します。
1 |
touch webpack.config.js |
このファイルは、webpackの設定ファイルです。
設定例は、ここを確認してください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# 設定例 module.exports = { module: { rules: [ // ... other rules omitted // this will apply to both plain `.scss` files // AND `<style lang="scss">` blocks in `.vue` files { test: /\.scss$/, use: [ 'vue-style-loader', 'css-loader', 'sass-loader' ] } ] }, // plugin omitted } |
関連記事
style
scopedについて
styleタグにscopedをつけると、そのファイル内のコンポーネントのみstyleが適用されます。
1 2 3 4 5 6 7 8 9 |
<template> <div class="hoge-container">hoge</div> </template> <script scoped> .hoge-container { /* 上記のhoge-containerのみstyleを適用 */ } </script> |
小技
v-forによるレンダリング
以下のようにコンポーネントを複数記述するのではなく、v-forを使ったレンダリングにて対処できます。
1 2 3 4 5 6 7 8 9 10 11 |
<template> <div class="todo-list"> <TodoItem title="Walk the dog" description="Go to the Dog" /> <todo-item v-bind:title= "'Buy a bread'" v-bind:description="'Whole grain bread would be good'" /> <todo-item :title="todoTitle" :description="todoDescription"/> </div> </template> |
App.vue(Todoアイテム作成) -> TodoList.vue -> TodoItem.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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# App.vue (アイテムをセット) export default { ... data() { return { todos: [ { _id: "1", title: "Walk the dog", description: "Go to the Dog" }, ... ] } } } </script> # TodoList.vue (v-forを使ってレンダリング) <template> <div class="todo-list"> <TodoItem v-for="todo in todos" :key="todo._id" :title="todo.title" :description="todo['description']" /> </div> </template> <script> import TodoItem from './TodoItem.vue'; export default { components: { TodoItem, }, props: { todos: { required: true, type: Array } } } </script> # TodoItem.vue (Todoのコンポーネント) <template> <div> <div class="todo-item-content"> <div class="todo-item"> <div class="todo-item-content-title"> {{title}} </div> <div class="todo-item-content-description"> {{description}} </div> </div> </div> </div> </template> <script> export default { props: { title: { type: String, required: true, }, description: String, } } </script> |
プロパティ変更監視(watch)
watchを使用すると特定のプロパティが変更された時に行いたい処理を実装できます。
1 2 3 4 5 6 |
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <div id="app"> <button @click="increment">+1</button> <p>{{num}}</p> </div> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
new Vue({ el: '#app', data: { num: 0, }, methods: { increment() { this.num++; } }, watch: { num() { alert('Increment!') } } }); |
上記のコードでは、+1ボタンがクリックされた時、dataのnumプロパティが変化します。
それをwatchが検出し、num()関数を実行します。
watchのnumとdataのnumは一致していなければなりません。
子コンポーネントを参照(ref)
refを使うと子コンポーネントを参照できます。
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 |
// 親コンポーネント <template> <modal ref="modal"> // 子コンポーネント"modal"を参照 </modal> </template> <script> import Modal from "@/components/Modal"; export default { components: { Modal, }, data() { return { form: { title: "", description: "", }, forceClose: false, }; }, methods: { submitForm() { if (this.isFormValid) { this.$emit("formSubmitted", { ...this.form }); // 新しいobjectを作って渡す this.$refs.modal.close(); // 子コンポーネントのメソッドを実行 } }, }, }; </script> |
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 |
// 子コンポーネント <template> <div> <div class="modal-content"> <span class="close" @click="close" >×</span> <slot /> </div> </div> </div> </template> <script> export default { data() { return { isOpen: false, }; }, methods: { close() { // 親コンポーネントから使う this.isOpen = false; }, }, }; </script> |
親コンポーネントから参照したいコンポーネントをref=”modal”のようにしています。
そして、親コンポーネントから子コンポーネントのメソッドを$refsを使って呼び出すことができるようです。
propsを書き換えたい場合
propsは、作成後にその値を変更することができません。
しかし、propsから渡されたデータを書き換えたいという場合があると思います。
例えば、Todoアプリでは一度作成したTodoの内容を書き換えるときにpropsとして渡したデータを変更したい場合があります。
その場合は、「:value(v-bind:value)」を使うと書き換えることができます。
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 |
<template> <form class="app-form"> <div class="form-control"> <input :value="title" type="text" id="title" class="form-input" /> </div> <div class="form-control form-control-last"> <textarea :value="description" id="description" class="form-input" cols="30" rows="2" > </textarea> </div> </form> </template> <script> export default { props: { title: { type: String, required: true, }, description: String, }, </script> |
実際にデータを書き換えるためには、書き換え処理が必要ですが、上記はブラウザ上に表示したフォーム上で値を変更してもエラーが発生なくなるための変更です。
特定のデータを見つけて、更新する方法
まずはデータの見つけ方です。
次のデータ構造があるとします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
todos: [ { _id: "1", title: "Walk the dog", description: "Go to the Dog" }, { _id: "2", title: "Buy a bread", description: "Whole grain bread would be good" }, { _id: "3", title: "Learn Programming", description: "Preferable Tomorrow!" } ] |
この中から_id:2 を見つけたいとします。その場合は、findIndexを使うと良さそうです。
1 2 3 4 5 6 7 8 9 10 11 |
// _id: 2を更新したい var todoToUpdate = { _id: "2", title: "Buy a bread Update", description: "Whole grain bread would be good Update" }, // データ構造体をループし、条件がTrueniなった時点でその構造体のインデックスNoを返す const index = state.todos.findIndex(todo => { return todo._id === todoToUpdate._id; // }); |
JavaScriptの構造体は、0からカウントされるので、上記では「1」が返却されるはずです。
そして、Vue.setを使うと特定のデータを更新することができます。
1 2 3 |
import Vue from "vue"; Vue.set(state.todos, index, todoToUpdate); |
最近のコメント