0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Vue.js】入力値をリアルタイムで画面に反映する

Posted at

はじめに

イベントオブジェクトを取得することで、inputタグのvalue値を即時に画面表示する方法を記録。

イベントオブジェクト取得

inputイベント(要素のvalueの値が変化するたびに発生)でsetNameメソッドを発火させる。この時、イベントオブジェクトを取得するためにsetNameメソッドの引数にeventを設定。

HTML
  <body>
    <section id="events" v-cloak>
        <h2>Enter Your Name!</h2>
        <input type="text" @input="setName">
        <p>Your Name:{{ name }}</p>
    </section>
  </body>
Javascript
const app = Vue.createApp({
  data() {
    return {
      name:''
    };
  },
  methods:{
    setName(event){
      console.log(event)
    },
  }
}).mount('#events');

eventオブジェクトの中身
image.png

targetのタブをさらに開くとValueの項目があり、入力値が表示されている。
この値を使用することで、画面に入力値を表示できる。

image.png

入力値をそのまま表示Ver

HTML
  <body>
    <section id="events" v-cloak>
        <h2>Enter Your Name!</h2>
        <input type="text" @input="setName">
        <p>Your Name:{{ name }}</p>
    </section>
  </body>
Javascript
const app = Vue.createApp({
  data() {
    return {
      name:''
    };
  },
  methods:{
    setName(event){
      this.name = event.target.value;
    },
  }
}).mount('#events');

image.png

入力値を整形して表示Ver

setNameの引数に$eventを設定。

  <body>
    <section id="events" v-cloak>
        <h2>Enter Your Name!</h2>
        <input type="text" @input="setName($event,'山田')">
        <p>Your Name:{{ name }}</p>
    </section>
  </body>
const app = Vue.createApp({
data() {
  return {
    name:''
  };
},
methods:{
  setName(event,lastName){
    this.name = event.target.value + ' ' +  lastName;
  },
}
}).mount('#events');

image.png

終わりに

入力値をリアルタイムで反映できるのは、結構使い勝手が良いと感じた。
他のアプリケーション作成にも活用していきたい。

参考

Vueの勉強で活用中⇒https://www.udemy.com/course/vuejs-2-the-complete-guide/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?