Leveraging VueJS with Typescript to initialize reactive values in a class declaration

Recently, I have been exploring the idea of defining ref() or computed values in an external class to improve code structure and reduce clutter in .vue files.

For instance, consider a test.ts file like the one below:

import { ref, computed } from "vue";
import type { Ref, ComputedRef } from "vue";

export class Test {
    public refValue: Ref<number> = ref(0)
    public compValue: ComputedRef<string> = computed(() => {
        if (this.refValue.value === 0) return 'No Value given'
        else return `Value is ${this.refValue.value}`
    })

    constructor() {}

    public init() {
        this.refValue.value = 10
    }

}

And a Test.vue file structured as follows:

<template>
  <div v-if="test">
    <span>{{ test.refValue }}</span>
    <span>{{ test.compValue }}</span>
  </div>
<template>
<script setup lang="ts">
import { Test } from './Test.ts'
import { onMounted } from 'vue'

const test = ref<Test | null>(null)

onMounted(() => {
  test.value = new Test()
  test.value.init()
})
</script>

I attempted to implement this example, but encountered issues where the .ts file was overwriting the assigned ref() value for refValue. Consequently, when initializing at init(), a Type error occurred because there is no 'value' associated with 0.

This led me to the question: Is it feasible to approach it this way, and if so, what mistakes might I be making?

( Source : VueJS.org )

Answer №1

For more information, please refer to the Vue Docs. The ref() function is designed to unwrap nested refs as demonstrated below:

ref({
  refValue: ref(0),
  __proto__: Test,
})

// This is equivalent to
ref({
  refValue: 0,
  __proto__: Test,
})

Therefore, this.refValue = 0.

If you want to avoid this behavior, consider using shallowRef.

Check out this demo for a practical example.

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

How is it that changes to the ngOnInit variable don't impact the HTML in Angular 2/4?

I have a user object that I am subscribing to. If the user's name matches a certain value, then a button should not be displayed. I'm not sure why this is not affecting the ngIf in the HTML. Here is my HTML: <input *ngIf="showDelete" type="b ...

Issue an API request at a specific time in order to refresh the latest radio show in Angular2 utilizing RxJS

Currently, I am in the process of creating a schedule for a community radio station and I need help updating the current show that is airing. I have considered polling the server once a minute as a temporary solution, but I am unsure if this is the most ef ...

I'm experiencing issues with the automatic scrolling feature not working in my Angular Nebular Application when using Typescript

I'm facing an issue where after using router.navigateByUrl(""), I need to scroll back to the top. I've experimented with various methods, but none of them seem to be effective: window.scroll(0, 0); document.body.scrollTop = 0; document.querySel ...

Encountering problem with npm ERR! peer @angular/common@"^12.0.0" while trying to install @ng-bootstrap/[email protected]

Encountering an issue during the deployment of my Angular application. I added the @ng-bootstrap/ng-bootstrap package, but there seems to be a dependency resolution problem causing the issue. 22-Dec-2022 07:03:47 npm ERR! Could not resolve dependency: 2 ...

The data type 'Observable<any>' cannot be assigned to the type 'StoresSummaryResults'. The property 'Data' is not present in the 'Observable<any>' type

As a newcomer to using the Observable with Angular 2, I am facing an issue where my structure is not receiving the results despite being able to validate the response from my REST API. Below is the data class in Typescript that I have: import { RESTResul ...

Error encountered: ERESOLVE issue occurred while attempting to resolve dependencies during npm install

After attempting to run 'npm install' to download the dependencies from a cloned repository, an error appeared on the terminal. The operating system being used is Windows 10. npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: ...

Identify modifications to properties in Angular

What is the most effective method for responding to property changes within a component? I am seeking a solution that will trigger a specific function every time a property in a component is altered. Consider the following example with a single component: ...

The onChange Event triggers only once in a checkbox input

I am implementing a checkbox component that emits an event to the parent component. However, in the parent component, I am facing an issue where I need to perform different actions based on whether the checkbox is checked or not, but it seems to only work ...

Webpack is struggling to locate core-js paths when running on Windows operating systems

When running webpack, I am encountering the following errors: ERROR in ./node_modules/core-js/index.js Module not found: Error: Can't resolve './es' in 'pathtoproject\node_modules\core-js' @ ./node_modules/core-js/index. ...

Angular: Why Do Styles Fail to be Applied to Dynamically Inserted HTML Elements?

I am having trouble applying styles to a newly added "i" element as a child element to an HTMLDivElement. The styles set in the scss file are not being applied to the new element. Is there a way to ensure that the same styles are applied to the newly adde ...

Troubleshooting a NextJS Middleware Issue: Retrieving a Blank Screen After Token Verification

I'm currently developing a Spotify Clone using its API and utilizing Next JS Middleware to enforce redirect conditions. The purpose of these conditions is to verify if the user has a token; if not, they should be redirected to the login page. For som ...

Viewify - displaying images in v-data-table cells reveals only a portion of the image

I have a challenge with displaying avatars for users in a table. The rows are too small and the images are getting cut off. https://i.sstatic.net/QjkHj.png Table: <v-data-table :headers="tableHeaders" :items="streamers"> <t ...

Activating Modal in Angular 5 when Form is Submitted

I am currently integrating Angular 5 and Bootstrap 3 for a project. One of the forms on my website sends the input field data via email and includes a modal. I want to be able to trigger the modal based on a successful or error response from the server. I ...

Using words instead of symbols to represent logical operators

When coding in C++, I typically prefer using the 'word' operators: not instead of ! and instead of && or instead of || I find it easier to read, especially when negating statements with not. Is there a similar approach possible in ...

Unable to exclude modules from ng-build in Angular CLI, the feature is not functioning as intended

I am managing an Angular CLI project that consists of two identical apps. However, one app requires the exclusion of a specific module in its build process. Key Details: Angular CLI Version: 1.7.4 Angular Version: 5.2.10 In the angular-cli.json ...

Using Tailwind classes in Vue props

Looking to utilize a Vue prop within a Tailwind CSS class. The class in question is bg-[url('address')] (which sets the background image), with 'address' being the prop. Despite various attempts, I keep encountering the following erro ...

VueJS allows for collapsing all components at once, rather than just one

I'm seeking clarification on the following code: <div id="foo"> </div> <script type="text/x-template" id="collapsible"> <div class="wrapper"> <div class="header" v- ...

Router outlet fails to load identical child component

Currently, I am working on developing a file upload interface with both grid and list views for the files. These views are separate components under a shared parent Preview component. Surprisingly, the TypeScript files for both the grid and list views are ...

Issue with Vue Router failing to navigate to the correct hash location

After clicking a link on the app, I noticed that the Router does scroll to the correct hash location, but it always seems to be one element too high on the page. This issue occurs even though the scrolling functionality is working fine. For instance, if my ...

Creating an exportable class in Typescript and Node.js is a crucial aspect of

I've encountered an issue while trying to create a separate class file for import from the controller. It seems that declaring variables inside the class is not working as expected. Below is the class I intend to export: const fs = require("fs&q ...