
【Vue.js】最小限の構成で「Hello, Vue.js!」を表示する
実験的に、サーバを立てることなく Vue.js を動作させたく思い、最小限の構成で変数内に指定した文字を表示する方法をポストします。
最小限の構成で「Hello, Vue.js!」を表示する
サーバを立てず、普通のHTMLのように、エクスプローラのパスをブラウザに入力して Vue.js を動作させる方法です。
用意するのは3ファイル。
- index.html
- js/main.js
- css/main.css
ルートディレクトリは人二の場所で構いませんが、日本語が入っていると面倒くさいので、
私は下記のように、ドキュメントの下に「vue3」ディレクトリを作成し、その中に設置しました。
「UserName」は、各人のユーザ名が入っていると思います。
index.html
パスは C:\Users\UserName\Documents\vue3\test1\index.html
です。
CDNを使って Vue.js を読み込んでいます。バージョンは任意で。
マスタッシュ構文で message
をプリントしているだけの内容です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue.js 3</title> <link rel="stylesheet" href="css/main.css"> </head> <body> <div id="app"> {{ message }} </div> <script src="https://unpkg.com/vue@3.2.47"></script> <script src="js/main.js"></script> </body> </html> |
js/main.js
パスは C:\Users\UserName\Documents\vue3\test1\js\main.js
です。
message 変数に「Hello, Vue.js!」を代入しているだけです。
また、index.html の div タグで app を指定している領域に対し、vue.js 内容を適応させるとしています。
1 2 3 4 5 6 |
const app = Vue.createApp({ data: () => ({ message: 'Hello, Vue.js!' }) }) app.mount('#app') |
css/main.css
パスは C:\Users\UserName\Documents\vue3\test1\css\main.css
です。
スタイルシートの内容は何もなくファイルを用意するだけ。
構成図
└ [test1]
├ [js]
│ └ main.js
├ [css]
│ └ main.css
└ index.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 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 73 74 |
const EditableTable = { template: ` <div> <table border="1"> <thead> <tr> <th>ID</th> <th>名前</th> <th>アクション</th> </tr> </thead> <tbody> <tr v-for="item in items" :key="item.id"> <td>{{ item.id }}</td> <td> <input v-if="editingId === item.id" v-model="editableName" > <span v-else>{{ item.name }}</span> </td> <td> <button v-if="!isEditing(item)" @click="startEdit(item)">編集</button> <span v-else> <button @click="saveEdit(item)">保存</button> <button @click="cancelEdit">キャンセル</button> </span> </td> </tr> </tbody> </table> </div> `, data() { return { items: [ { id: 1, name: "田中" }, { id: 2, name: "佐藤" }, { id: 3, name: "鈴木" }, ], editingId: null, editableName: "", previousName: "", }; }, methods: { isEditing(item) { return this.editingId === item.id; }, startEdit(item) { this.editingId = item.id; this.previousName = item.name; this.editableName = item.name; }, saveEdit(item) { const target = this.items.find(i => i.id === item.id); if (target) { target.name = this.editableName; } this.editingId = null; }, cancelEdit() { const target = this.items.find(i => i.id === this.editingId); if (target) { target.name = this.previousName; } this.editingId = null; } } }; const app = Vue.createApp({}); app.component("editable-table", EditableTable); app.mount("#app"); |