Upgrade Vue by utilizing a class object attribute

I have created a unique class with properties and I am trying to figure out how to update my vue file to reflect any changes made to the properties. I have simplified the class for now, but plan to expand it with more properties in the future.

In this specific case, I want a button to change its color and icon when clicked by the user, based on the value of the 'isPlaying' property in 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();
    }
  }
}

Answer №1

If you want to achieve reactivity in the properties of the Stopwatch instance, consider using reactive instead of computed:

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

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

Check out the demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing a continuous running test loop

Currently, I have a code that runs fine, but I am looking to modify it to run in a loop that counts the number of elements with the class="socal" and tests each link. module.exports = { 'Unitel Fitness - click' : function (browser) { bro ...

What techniques should be employed for handling object props in VueJS?

I am currently working on a Vue Component that serves as a form for creating or editing patient information. This form includes fields for birth name, first name, date of birth, birth place, gender, and more. When it comes to maintainability, reactivity, ...

What is the proper way to correctly invoke NuxtServerInit?

Code snippet from the VUEX repository: export const state = () => ({ z: 'sdfjkhskldjfhjskjdhfksjdhf', }); export const mutations = { init_data_for_firmenistorie2 (state, uploadDbFirmenistorieData){ state.z = uploadDbFirmenistorieD ...

Troubleshooting Client Side Deep Links: Resolving WebpackDevMiddleware 404 Errors

While utilizing the WebpackDevMiddleware for Development builds to serve a Vue.js application with client-side routing, I encounter an issue. The SPA application loads fine from the root url, but any attempt to access client-side deep links results in a 40 ...

Top method for dynamically loading a specific component by using its selector as a variable

I'm currently in the process of developing a straightforward game using Angular. The game is structured to consist of multiple rounds, each with unique characteristics that are distinguished by the variable roundType. For instance, round types can in ...

Webpack 5: Updating the file path for TypeScript declaration files

My project structure includes a crucial src/ts folder: - dist/ - js/ - css/ - index.html - about.html - src/ - assets/ - fonts/ - images/ - sass/ - ts/ - services/ - service1.ts - ...

Setting up Vite with Vue 3 necessitates the use of multiple application output directories

I have 2 separate Vue 3 applications set up using Vite with unique entry points within a larger project. These apps are built automatically with watch using the build script in package.json. My goal is to have distinct output folders for each of the 2 Vue ...

Cell renderers in Angular do not receive the ICellRendererParams during initialization

I am currently working on creating a cell renderer in Angular that converts IP addresses into clickable SSH links. Below is the code for the renderer component: import { Component, OnInit, OnDestroy } from "@angular/core"; import { DomSanitizer, ...

How to retrieve a value only if it is truthy in JavaScript or TypeScript - Understanding the operator

In React components, a common scenario arises with code like this: <Carousel interval={modalOpen ? null : 8000}> It would be great if I could simplify it to something along these lines (although it's not valid): <Carousel interval={modalOpen ...

Why aren't enums that can be derived supported?

Is there a way to create an enum that is a subset of another enum? Sometimes it would be useful to have an enum that is a subset of another Enum with the same values at run time but under a different name. Are there better ways to handle this scenario? ...

Encountering an issue while trying to import the validator module in NextJS 13

I encountered a peculiar issue while trying to import a module. Nextjs presented the following error message: ./application/sign_in/sign_in_store.ts:2:0 Module not found: Can't resolve 'validator' 1 | import { createEvent, createStore } fr ...

fetching data with Contentful and GatsbyJS

I am currently working on fetching data from Contentful using GraphQL within a Gatsby application, and here is my approach: type AllContentfulBlogs = { allContentfulBlogs: { nodes: Array<{ title?: string | null | undefined, ...

Pattern matching for validating multiple email addresses

I need assistance with validating multiple email inputs using regex in Angular. I am looking to enforce a specific format for the emails, such as: Examples: *****@zigurat.com *****@test.com *****@partlastic.com The ***** can be any characters, but the ...

Angular: encountering template parse errors with unknown <component> element

I'm struggling to import a component into another component, but the imported component cannot be found. Here is the error message: Uncaught Error: Template parse errors: 'aktenkorrespondenzenTemplate' is not a known element: 1. If 'ak ...

Tips for declaring a non-reactive instance property in Vue.js with TypeScript

I am currently in the process of transitioning my Vue.js components to TypeScript. In accordance with the recommendations provided in the documentation, I attempted to utilize Vue.extend() for my component implementation. The code snippet for my component ...

Steps for setting up tsconfig.json for Chrome extension development in order to utilize modules:

While working on a Chrome plugin in VS Code using TypeScript, I encountered an issue with the size of my primary .ts file. To address this, I decided to refactor some code into a separate module called common.ts. In common.ts, I moved over certain constan ...

Looking for guidance on integrating Forms with VueX and script setup? Are you utilizing v-model in your implementation?

UPDATE: I'm contemplating whether or not to abandon VueX entirely due to its outdated status, with Pinia being the preferred choice nowadays. Can someone confirm this? https://stackblitz.com/edit/vue-script-setup-with-vuex-hmrk5d?file=src/store.ts ...

typescript when an argument is missing, it will automatically be assigned

Here is my TypeScript function: function more(argv: {a: number, b?: string}): number{ console.log( b) return a } I am invoking the function this way: let arc = more({a: 5}) Unexpectedly, I see 10 in the console. I was anticipating undefined ...

Setting up dynamic paths for a template's source in Vue.js

My Vue application is structured into components as shown below: https://i.sstatic.net/ZapkE.jpg I am trying to dynamically bind the src property in the <template> so that each time a user requests a different template, a different path is loaded. h ...

What Type of state does Typescript expect in React?

Whenever I attempt to pass the state in my TypeScript-based React application using any to a function, I encounter a tslint error. no-any: The use of 'any' for type declaration compromises type safety. It is recommended to replace it with a mo ...