Search code examples
javascriptvue.jsref

Why in Vue 3, when using a function (with the ref property) to bind the dynamic value of a class, the class can change when the ref value changes?


I'm trying to write Vue code like this.

<template>
  <h1 :class="{ disabled: aClass() }">Hello</h1>
</template>

<script setup lang="ts">
import { ref } from "vue";

const a = ref(1);

function aClass() {
  if (a.value === 2) {
    return true;
  }
  return false;
}

setTimeout(()=>{
   a.value = 2;
}, 3000)

setTimeout(()=>{
   a.value = 1;
}, 6000)

</script>

<style>
.disabled {
  background: red;
  color: blueviolet;
}
</style>

When I change a.value twice, the function seems to be called again, which confuses me.

I would like to know why the background of <h1 :class="{ disabled: aClass() }">Hello</h1> changes colors twice.

Thanks.


Solution

  • Binds in Vue templates are actually computed.

    <template>
      <!-- what you write -->
      <h1 :class="{ foo: bar() }">Hello</h1>
      <!-- what it actually does -->
      <h1 :class="computed(() => ( {foo: bar()} ))">Hello</h1>
    </template>
    

    so they update automatically whenever thier dependencies change