Tips for utilizing ES6 classes in Vue.js for code reusability

Seeking guidance on integrating existing ES6 classes with Vue Js.

I currently have a class where a variable is being updated by an observable function.

class A { 
    public a: string;
    someobservable.subscribe((a) =>{
         this.a = a;
    })
}

Within Vue.js, I have instantiated an object of this class.

Here's a sample of how the property is utilized:

created: {
    objA = new A();
}
methods: {
    getA() {
        if(this.objA !== undefined){
            return objA.a;
        }
    }
}

In the Vue template:

<div>{{getA()}}</div>

However, there seems to be a synchronization issue between the template value and the class variable.

Are there alternative methods for ensuring real-time updates in the Vue template when using properties?

Answer №1

To improve efficiency, consider using getA() as a computed property instead of a method. Additionally, you can eliminate the if statement since a return statement without a value will automatically return undefined.

computed: {
  getA() {
    return objA.a;
  }
}

Answer №2

When creating an instance, it is important to do so within the appropriate scope. To ensure that Vue can track any changes, instantiate your object in the data field.

data: {
    objA: new A();
},

Subsequently, you have the option to implement a method as shown below:

methods: {
    getA() {
       return this.objA.a;
    }
},

<div>{{getA()}}</div>

Alternatively, consider utilizing a computed property as suggested by others:

computed: {
    getA() {
       return this.objA.a;
    }
}

<div>{{getA}}</div>

Both approaches yield similar results, but incorporating a computed property is recommended for caching benefits.

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

I am looking for string validation in Angular

Hello, I have just one input box where I enter a 10-digit string, and I am looking to apply the following validations to the entered string: The first 4 characters should be alphabets The characters from 5 to 9 should be numeric The last character should ...

Accessing environmental variables from pug template

Currently, I am utilizing pug to generate static HTML for my own customized static site builder. In my package.json file, the only line of Node.js server code present is: "watch-pages": "pug -O options.json -w pages/ --out _static-website/" However, the ...

Is there a way to stop myself from accidentally clicking twice on the same tile?

I'm currently working on a game and facing an issue where my "X" gets deleted when clicking twice on the same tile. I am able to move my "X" around, but the double-click deletion is causing trouble. I attempted using booleans but struggle with them. I ...

React Hooks: Unable to re-enable input after it has been disabled

Attempting to manage the status of my points input whether it's enabled or disabled, I encountered an issue. Upon checking the checkbox, it correctly gets disabled. However, upon unchecking it, the input remains disabled. Initially, I attempted settin ...

Generating Unique Random Numbers with JavaScript

Is there a way to generate 5 unique random lottery numbers using JavaScript? I've been working on the code below, but can't seem to figure out how to ensure there are no duplicate numbers in the final selection. I tried adding conditionals and lo ...

Using the goBack function in React Router does not add the previous location to the stack

In React Router v4, I have a list page and a details page in my web application. I want to implement a 'Save and close' button on the details page that redirects the user back to the list page when clicked. However, I noticed that after the user ...

emulating the behavior of a synchronous XmlHttpRequest

While I have taken the time to explore similar questions like Pattern for wrapping an Asynchronous JavaScript function to make it synchronous & Make async event synchronous in JavaScript, I want to ensure that I consider all potential solutions. Is it ...

Detecting collisions between two squares in an HTML5 canvas

class Snake { constructor() { this.x = 400; this.y = 400; this.width = 25; this.height = 25; } draw() { ctx.fillRect(this.x, this.y, this.width, this.height); } } let snake = new Snake(); class ...

Filtering function that works without specific knowledge of keys

I'm working on a JavaScript method to filter a list dynamically without knowing the specific key (s). I've made some progress, but I'm stuck and not sure how to proceed. The foreach loop I have isn't correct, but I used it for clarity. ...

Resetting the Angular provider configuration whenever the service is injected into a different location

Trying to wrap my head around a rather complex issue here. I have a service set up as a provider in order to configure it. Initially, this service has an empty array of APIs which can be dynamically added to by various configuration blocks. When adding API ...

How can serverless platforms handle binary data such as PDF files?

I am currently experiencing an issue that involves uploading a PDF file in Vue.js to a serverless Node.js application, resulting in broken file content. This problem occurs due to the serverless platform incorrectly parsing binary data types. How can I e ...

Adding a collection of items to an array in preparation for organizing

Realizing that sorting objects is not feasible - despite the necessity of having the object values sorted - I conclude that the only option is to move the object array content into a new array for sorting purposes. The following code generates the output ...

Converting a string to JSON format with JavaScript

My string is structured in JSON format like this: "{""c1"": ""value1"", ""c2"": ""value2""}" After storing it in an SQLITE database, I use the following Javascript code to retrieve it back as JSON: var req= "SELECT json_column from my_table"; var re ...

The lodash debounce function is being triggered multiple times instead of just once, causing issues with my react hooks in a react native environment

Currently, I am implementing a search feature for multiple objects in an array that triggers onChange of the text Input. To optimize this process, we need to incorporate a debouncing function to prevent unnecessary API calls to the search function. Howeve ...

Manipulating state in React

Currently, I am enrolled in Samer Buna's Lynda course titled "Full-Stack JavaScript Development: MongoDB, Node and React." While working on the "Naming Contests" application, I encountered a piece of code within the App component that has left me puzz ...

Using a Vue component to send a form for submitting data into the backend database of a Django application

Where should the connection between a form within a Vue component and a Django backend be established? In my frontend, I am utilizing VueJS where my primary component can retrieve data from a JSON file through an API specified in my Django view and URL fi ...

Guide to creating JSDoc for a TouchEvent handler

Looking to improve my shorter-js codebase with JSDoc for TypeScript definitions, but hitting a roadblock. I've implemented the on() function using Element.addEventListener, working well so far. However, when passing a TouchEvent as a parameter for an ...

Decimal tally in React using JavaScript

I'm struggling with my counter code that is supposed to count from 0 up to a given number, but it seems to have issues with decimals. For example, if it's set to count to 4.5, it stops at 4.1 or when counting from 0 to 5.7, it stops at 5.1. I&apo ...

react-i18next - The function call does not match any overload when the specified type is `string`

I am currently utilizing react-i18next in conjunction with React and TypeScript. Interestingly, when I attempt to load a property using a string literal and type inference, everything works seamlessly. However, once I specify the type as string, an error i ...

Accessing JSON Data Using JQUERY

Currently, I am experimenting with grabbing JSON data from websites using the $.getJSON() method. Here is the code snippet I have been working on: The website I am attempting to retrieve JSON data from can be found here. Interestingly, the code functions ...