Home » vue » Update Vue from Class Object property

Update Vue from Class Object property

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a custom class that contains properties and I’m wondering how can I have my vue file update to reflect the property change. For the sake of simplicity I’ve slimmed down my custom class (which i’ll expand in the future to have more properties.

In this example, i expect the btn to change color and icon when the user clicks it based on the property ‘isPlaying’ on my custom class Stopwatch.

main.vue

<template>
  <q-page padding class="text-center q-pa-md">
    <q-btn
        :color="sw.isPlaying ? 'red' : 'green'"
        :icon="sw.isPlaying ? 'mdi-pause' : 'mdi-play'"
        @click="sw.toggle()"
    />
  </q-page>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  computed,
  onMounted,
  onUnmounted
} from '@vue/composition-api';
import Stopwatch from 'src/utils/stopwatch';

export default defineComponent({
  name: 'Stopwatch',
  components: {},
  setup() {
    const sw = computed(() => new Stopwatch());
    return {
      sw
    };
  }
});
</script>

stopwatch.ts

export default class Stopwatch {
  isPlaying: boolean;

  constructor() {
    this.isPlaying = false;
  }

  // Start timer or continue from paused time
  startTimer() {
    this.isPlaying = true;
    console.log('play');
  }

  // Stop/Pause the timer
  stopTimer() {
    this.isPlaying = false;
    console.log('stop');
  }

  // Start/Stop timer or continue from paused time
  toggle() {
    if (this.isPlaying) {
      this.stopTimer();
    } else {
      this.startTimer();
    }
  }
}
Answers:

Instead of computed, use reactive to make the Stopwatch instance’s props reactive:

import { defineComponent, reactive } from '@vue/composition/api'

export default defineComponent({
  setup() {
    const sw = reactive(new Stopwatch());
    return {
      sw
    };
  }
});

demo