1
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?

Vue.jsのv-onの基礎とjQueryとの比較

Last updated at Posted at 2025-10-19

v-onについて

v-onはイベントをハンドリングするために使用されます。

sample.vue
<script setup>
function sampleFunction() {}
</script>
<template>
<button v-on:click="sampleFunction">ボタン</button> <!-- ボタンをクリックすると、sampleFunctionが実行される -->
</template>

v-onは非常によく使われるため、「v-on:」を省略して「@」と記載ができます。

sample.vue
<script setup>
function sampleFunction() {}
</script>
<template>
<button @click="sampleFunction">ボタン</button> <!-- @clickで記載した場合 -->
</template>

jQueryとの比較

やりたいこと

  • ボタンをクリックすると表示される文言が切り替わる

Vue.jsでの実装

sample.vue
<script setup>
import { ref } from 'vue'
const message = ref('初期表示') // リアクティブな変数を宣言
function sampleFunction() {
  // スクリプト内でrefで宣言した変数は.valueを付けて値を取得する
  message.value = message.value === '初期表示' ? '切り替え表示' : '初期表示'
}
</script>
<template>
<button @click="sampleFunction">ボタン</button>
<p>{{ message }}</p>
</template>

jQueryでの実装

sample.html
<p id="message">初期表示</p>
<button class="change-button">button</button>
<script>
$(document).ready(function() {
    let message = "初期表示";
    $(".change-button").on("click", function() {
        message = message === "初期表示" ? "切り替え表示": "初期表示";
        $("#message").text(message);
    });
});
</script>

ポイント:イベントハンドリングと画面更新の比較

  • Vue.jsでは、refを使って リアクティブ なデータを定義します。データ(message)を変更するだけで、自動的に画面(DOM)が更新されます
  • jQueryでは、要素の セレクタ を使ってDOM要素を特定し、text()メソッドなどで DOMを直接操作 する必要があります
1
0
2

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
1
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?