Vue.js テキストフォームに入力された文字列を表示する

  • 作成日 2022.01.31
  • 更新日 2022.02.28
  • Vue.js
Vue.js テキストフォームに入力された文字列を表示する

Vue.jsで、テキストフォームに入力された文字列を表示するサンプルコードを記述してます。 「vue3」を使用してます。

環境

  • OS windows10 pro 64bit
  • Vue.js 3.0.0
  • Apache 2.4.43
  • ブラウザ chrome 92.0.4515.107

テキストフォームに入力された文字列を表示

文テキストフォームに入力された文字列を表示させるには、「v-model 」を使用します。

以下は、テキストフォームに文字を入力すると、「p」タグ内にバインディングされた文字列「val」を表示させるサンプルコードとなります。

※「vue3」は「cdn版」、デザインは「semantic-ui」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- semantic.css  -->
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
  <script src="https://unpkg.com/vue@next"></script>

</head>
<style>
  body>.grid {
    height: 100%;
  }

  .fields {
    margin-top: 5px;
  }
</style>

<body>
  <div id="app" class="ui middle aligned center aligned grid">

    <div class="column">

      <form class="ui fluid form">
        <div class="inline field">
            <input id="txt" type="text" v-model="val">
            <p id="lab" class="ui green tag label">{{val}}</p>
        </div>
    </form>

    </div>

  </div>
  <script>

    const app = {
      data() {
        return {
          val: ''
        }
      }
    }

    Vue.createApp(app).mount('#app')
    
  </script>
</body>

</html>

表示されていることが確認できます。