Vue.js v-ifとv-modelのサンプルコード

v-ifとv-modelの基本的な使い方
環境
- OS CentOS Linux release 8.0.1905 (Core)
- node V10.16.3
- npm 6.9.0
- @vue/cli 4.0.5
※centos8にVue.jsの環境構築手順はこちら
仕様
初期画面

テキストボックス に文字列を入力すると、入力した文字列が表示される

「clear」ボタンをクリックすると、テキストボックスの文字列が全て削除され「テキストを入力して下さい」という文言が表示される

サンプルコード
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 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 |
<template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png"> <h3 v-if="msg.length > 0"> 入力テキスト表示<br> {{msg}} </h3> <h3 v-else> テキストを入力して下さい </h3> <input class="input" type="text" v-model="msg"> <button class="button" @click="clear()">clear</button> </div> </template> <script> export default { data () { return { // デフォルトの表示される文字列{{msg}}にデータバインディング msg: '文字列入力' } }, // ボタンクリックで発生するイベント methods: { clear () { // 文字列消去する this.msg = '' } } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 120px; } .input{ width: 130pt; height:20pt; } .button { display: block; position: relative; margin: 0 auto; width: 70pt; border: solid 1px silver; border-radius: 0.5rem 0.5rem; padding: 0.5rem 1.5rem; margin-top: 1rem; text-decoration: none; } </style> |
v-if=”msg.length > 0 “により msg に文字列があるかを判定し、v-elseがそれ以外の条件となります
1 2 3 4 5 6 7 8 |
<h3 v-if="msg.length > 0"> 入力テキスト表示<br> {{msg}} </h3> <h3 v-else> テキストを入力して下さい </h3> |
v-model=”msg”により、テキストボックスと msg がデータバインディング される
1 |
<input class="input" type="text" v-model="msg"> |
main.js とindex.html
src/main.jsはインストール時のまま
1 2 3 4 5 6 7 8 9 |
import Vue from 'vue' import App from './App.vue' Vue.config.productionTip = false new Vue({ render: h => h(App), }).$mount('#app') |
render: h => h(App) について
1 2 3 4 5 6 7 8 9 |
render: h => h(App) は render: function(createElement){ return createElement(App) } とまったく同じで h はhyperscriptという意味らしい |
public/index.htmlもインストール時のまま
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html lang="en"> <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"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <title>vuedef</title> </head> <body> <noscript> <strong>We're sorry but vuedef doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> </body> </html> |
-
前の記事
CentOS7 に Vim エディタをインストールする 2019.10.31
-
次の記事
windows10 Hyper-VにUbuntu19.10をインストールする 2019.11.01
コメントを書く