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?

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

Posted at

v-bindについて

v-bindは属性やコンポーネントの props を式に動的にバインドします。

sample.vue
<script setup>
const imageSrc = "images/test1.jpg"
</script>
<template>
<img v-bind:src="imageSrc" /> <!-- スクリプトの imageSrc の値が src 属性にバインドされる-->
</template>

v-bind は非常によく使われるため、「v-bind」を省略して書くこともできます。

sample.vue
<script setup>
const imageSrc = "images/test1.jpg"
</script>
<template>
<img :src="imageSrc" /> <!-- :src と書けば src 属性に値がバインドされる -->
</template>

さらに属性名とスクリプトの変数名が一致していれば変数名の指定も省略できます。

sample.vue
<script setup>
const src = "images/test1.jpg"
</script>
<template>
<img :src /> <!-- スクリプトの src の値がバインドされる -->
</template>

jQueryとの比較

やりたいこと

  • ボタンを押下する事により、リンクの遷移先を切り替える

Vue.jsでの実装

sample.vue
<script setup>
import { ref } from 'vue'
const linkUrl = ref("https://vuejs.org/")
function changeUrl() {
    linkUrl.value = "https://github.com/"
}
</script>
<template>
<a :href="linkUrl" target="_blank">リンク</a>
<button v-on:click="changeUrl">button</button>
</template>

jQueryでの実装

sample.html
<a href="https://jquery.com/" target="_blank" class="change-link">リンク</a>
<button class="change-button">button</button>
<script>
$(document).ready(function() {
    // ボタンがクリックされた時の処理を定義
    $(".change-button").on("click", function() {
        $(".change-link").attr("href", "https://github.com/");
    });
}
</script>

ポイント

  • Vue.js は、:href="linkUrl"のように「データ(linkUrl)と属性(href)を結びつける」という宣言をするだけで、DOMを直接操作するコードは書かない
  • linkUrlのような リアクティブ なデータ(refで作成したデータ)の値を変更すると、Vueの リアクティブシステム がその変更を検知し、関連するDOM(この場合はリンクのhref属性)を自動で更新してくれる
  • jQuery は、$(".change-link")で要素を探し、.attr()で属性を書き換える、というようにDOMを 直接的・命令的 に操作している
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?