著者:大津 真
JavaScriptフレームワークの中でも、学びやすさと柔軟さで人気を集めている「Vue.js」。本連載では、Vue.jsの基礎から実践的な使い方までを、分かりやすく丁寧に解説していきます。一緒にフロントエンド開発の楽しさを体験してみましょう。第1回では、Vue.jsの概要と、簡単なアプリの作成方法を紹介します。
シェルスクリプトマガジン Vol.96は以下のリンク先でご購入できます。
図3 Options APIを利用したコードの例(抜粋)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<script type="module"> import { createApp } from 'vue' createApp({ data() { return { count: 0 } }, methods: { increment() { this.count++ } } }).mount('#app') </script> <div id="app"> <button @click="increment">Count is: {{ count }}</button> </div> |
図4 Composition APIを利用したコードの例(抜粋)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<script type="module"> import { createApp, ref } from 'vue' createApp({ setup() { const count = ref(0) function increment() { count.value++ } return { count, increment } } }).mount('#app') </script> <div id="app"> <button @click="increment">Count is: {{ count }}</button> </div> |
図5 SFCファイルの記述例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script setup> import { ref } from 'vue' const count = ref(0) </script> <template> <button @click="count++">Count is: {{ count }}</button> </template> <style scoped> button { font-weight: bold; } </style> |
図6 HTML文書のテンプレート例
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 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>Vueサンプル</title> </head> <body> <script type="importmap"> "imports": { "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js" } } </script> <script type="module"> import { createApp, ref } from 'vue' createApp({ setup() { // 処理はここに記述 } }).mount('#app') </script> <div id="app"> </div> </body> </html> |
図8 「sample1.html」ファイルに記述するコード
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 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>Vueサンプル</title> </head> <body> <script type="importmap"> { "imports": { "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js" } } </script> <script type="module"> import { createApp, ref } from 'vue' createApp({ setup() { const msg = ref('ハローVue') const person = ref({name:'大津真', age: 35}) return{ msg, person } } }).mount('#app') </script> <div id="app"> <h1>{{ msg }}</h1> <p>{{ person }}</p> </div> </body> </html> |
図10 setup()関数の定義コードをこのように変更
1 2 3 4 5 6 7 8 9 10 11 |
setup() { const msg = ref('ハローVue') const person = ref({name:'大津真', age: 35}) // 3秒後にリアクティブな変数msgを変更する setTimeout(() => { msg.value = "ようこそVueの世界へ" }, 3000) return{ msg, person } } |
図12 div要素の記述をこのように変更
1 2 3 4 |
<div id="app"> <h1>{{ "反転→ " + msg.split("").reverse().join("")}}</h1> <p>{{ `名前: ${person.name}, 年齢: ${person.age}才` }}</p> </div> |