著者:大津 真
JavaScriptフレームワークの中でも、学びやすさと柔軟さで人気を集めている「Vue.js」。本連載では、Vue.jsの基礎から実践的な使い方までを、分かりやすく丁寧に解説していきます。一緒にフロントエンド開発の楽しさを体験してみましょう。第3回では、HTMLやCSS、JavaScriptのコードをまとめた「SFCファイル」を使用したVueアプリケーションの作成について説明します。
シェルスクリプトマガジン Vol.98は以下のリンク先でご購入できます。
図6 「index.html」ファイルのbody要素
1 2 3 4 |
<body> <div id="app"></div> <script type="module" src="/src/main.js"></script> </body> |
図7 「src/main.js」ファイルの内容
1 2 3 4 5 |
import { createApp } from 'vue' import './style.css' import App from './App.vue' createApp(App).mount('#app') |
図8 デフォルトの「src/App.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 |
<script setup> import HelloWorld from './components/HelloWorld.vue' </script> <template> <div> <a href="https://vite.dev" target="_blank"> <img src="/vite.svg" class="logo" alt="Vite logo" /> </a> <a href="https://vuejs.org/" target="_blank"> <img src="./assets/vue.svg" class="logo vue" alt="Vue logo" /> </a> </div> <HelloWorld msg="Vite + Vue" /> </template> <style scoped> .logo { height: 6em; padding: 1.5em; will-change: filter; transition: filter 300ms; } (略) </style> |
図9 CDN版のVueアプリケーション「counter1.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 33 34 35 36 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>Vueサンプル</title> <style> h1 { font-size: 3em; background-color: #f0f0f0; color: green; } </style></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 counter = ref(0) function increment() { counter.value++ } return { counter, increment } } }).mount('#app') </script> <div id="app"> <h1>カウント: {{ counter }}</h1> <button v-on:click="increment">+</button> </div> </body> </html> |
図11 図9のVueアプリケーションの処理をApp.vueファイルに記述した例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<script setup> import { ref } from 'vue' const counter = ref(0) function increment() { counter.value++ } </script> <template> <h1>カウント: {{ counter }}</h1> <button v-on:click="increment">+</button> </template> <style scoped> h1 { font-size: 3em; background-color: #f0f0f0; color: green; } </style> |
図A 「vite.config.js」ファイルの変更例
1 2 3 4 5 6 7 8 |
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' // https://vite.dev/config/ export default defineConfig({ plugins: [vue()], base: '/myapp/' }) |