Is it possible to modify Vue data using a reference?

Consider this scenario to illustrate my issue.

For instance: I have a Person class structured like this

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    celebrateBirthday() {
        console.log("Happy Birthday");
        this.age += 1;
    }
}

and in Vue, I implement this class as follows

data() {
    return {
        person: new Person("Kireeti", 26)
    }
},
mounted() {
    this.person.celebrateBirthday();
}

typically, we might do

mounted() {
    this.person.age += 1 
}

however, I prefer handling it within the class itself for various reasons. This approach functions correctly due to object references. Nevertheless, I am curious if this is an acceptable practice?

Any thoughts or insights on this matter?

Answer №1

When working with objects in components like demonstrated below:

data() {
    return {
        person: new Person("Kireeti", 26)
    }
},
mounted() {
    this.person.celebrateBirthday();
}

This method is arguably more advantageous compared to simply incrementing

this.person.age += 1</code within the component.</p>

<p>The rationale behind this is that while increasing a person's age by 1 is straightforward, there could be more intricate conditions for other objects. Perhaps you may want to introduce constraints within the <code>celebrateBirthday
function or make additional changes to the person's attributes beyond just altering their age.

It is preferable not to handle such logic within a Vue component, especially considering that other components may also utilize instances of the Person class. Keeping this logic within the class itself appears to be the more suitable approach.

Potential Concerns

Issues relating to object references typically stem from matters of reactivity. For instance, if the Person class includes an array of friends, and your component relies on monitoring its changes through code like:

<friend-component v-for="friend in friends" :data="friend" />

You must exercise caution when modifying the internal friends array within the person object in a manner that ensures compatibility with Vue's reactive tracking mechanisms. It is important to note that neither Sets nor Maps can be reliably used for this purpose, and there exist several other limitations as well. Additionally, remember to specify {deep: true} when observing modifications to objects.

Nevertheless, whether it pertains to variables associated with your Vue component or those belonging to an object, the principles regarding object references remain consistent without any major drawbacks as far as my knowledge extends.

Answer №2

I suppose there's no problem with utilizing it in a traditional manner.

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

Two separate buttons in two distinct views that trigger the same function in AngularJS

I am currently working on a Single Page Application (SPA) that has two distinct views - one for subjects and another for students. In the subject view, there is a save button located in app/views/subject/subject.html: <button type="button" class="b ...

I would like to terminate the property when processing it on a mobile device

<div class="col-sm-24 embed-responsive"> <iframe width="100%" src="http://www.youtube.com/embed/${item.snippet.resourceId.videoId}"></iframe> </div> .embed-responsive iframe { height: 185px; margin-top: -4%; paddin ...

Facing continuous 404 errors while working with nodejs and express

While attempting to collect data from a local host webpage's registration form that captures user information, I encounter an issue upon pressing the submit button A 404 Error is displayed stating "page not found", preventing the collection and out ...

extract information from a JavaScript string

I have a sequence that looks like this: coordinates = '15,-2,-3,15' This sequence corresponds to points, specifically A(15, -2), B(-3, 15). Q How can you retrieve the data from a string in this format? It would be ideal to obtain the results ...

Utilizing MongoDB query for geoLocation with maxDistance parameter

Customer location: customerCoordinates: [83,24] stores: { id:1, location: {coordinates:[85,44]...} maxRadiusDelivery: 2000 //meters }, { id:2, location: {coordinates:[82,34]...} maxRadiusDelivery: 100 //meters } Query: db.wh.find({ 'locati ...

Issue with Laravel VueJs: Unable to render the component using `router-view`

While similar questions exist on this site, none have resolved my issue. Thus, I am presenting my question here: In my Laravel 5.3 and VueJs application, the root instance of Vue in the app.js file points to App.vue. Inside App.vue, I have a router-view p ...

Searching for the search parameter in the Wordpress admin-ajax.php file. What could it

Just diving into the world of php and wordpress. Are there any search parameters I can include in admin-ajax.php? Here are the parameters in the ajax post; action: rblivep data[uuid]: uid_search_0 data[name]: grid_small_1 data[posts_per_page]: 8 data[pagin ...

What is the best way to modify the style class and content of text for parent elements in this d3.js tree structure?

This is a follow-up to this question. (Special thanks to Cyril for the assistance!) There is a slight complication with my issue and I require further assistance. When a user clicks on any text element of a node, I aim for the following actions to take pl ...

Implementing a dynamic table filter for every column using AngularJS

I have been working on a project to create a custom directive that generates a table with dynamic data and allows for sorting of columns. While the sorting function works as intended, I now want to implement filtering on all columns without specifying a sp ...

Update the contents of a neighbor div within the same parent element using jQuery

Attempting to set the range slider value within the slider parent sibling var updateRangeSlider = function() { var slider = $('.range-slider'), range = $('.range- value = $('.range-slider__value'); sli ...

Typescript is throwing an error with code TS2571, indicating that the object is of type 'unknown'

Hey there, I'm reaching out for assistance in resolving a specific error that has cropped up. try{ } catch { let errMsg; if (error.code === 11000) { errMsg = Object.keys(error.keyValue)[0] + "Already exists"; } return res.status ...

The NgModel does not accurately show the chosen value in a dropdown menu that is populated based on the selection of another dropdown

After the component loads, I expect both mainTask and mainJob to be displayed as selections in the dropdown. However, only mainTask is updated while mainJob remains unchanged in the UI. Interestingly, when I manually choose a value from the taskList dropdo ...

Initiate a second click action when the button is clicked for the first time

Upon clicking the "Continue" button in my HTML, an overlay is displayed. This overlay contains a "Skip and Continue" button. My goal is to have the second overlay appear directly on the first click of the "Continue" button, without the initial overlay show ...

Code executing twice instead of once in Javascript

Having trouble with a script in my demo below. When I enter "first input", submit, then click on the returned "first input", it alerts once as intended. However, upon refresh, if I enter "first input", submit, then add "second input", submit, and finally c ...

Using React.PureComponent, the list component efficiently renders each item with optimized performance

We've developed a reusable list component in ReactJS. To address performance concerns, we decided to incorporate the shouldComponentUpdate method to dictate when our list component should re-render. public shouldComponentUpdate(nextProps: TreeItemInt ...

Is there a way to showcase the results of a countdown timer script within an HTML code?

I'm currently working on a way to incorporate the results of this online timer script into another script. Below is the timer script that I came across: // Setting the target date for the countdown var countDownDate = new Date("Jan 5, 202 ...

Attempting to transmit a value from an ASP.NET JavaScript script to my C# Code Behind function by utilizing a Hidden Field

I am encountering an issue with my ASP.NET Web site where I cannot retrieve a value from a JavaScript function in my C# Code Behind. The value is passed as an argument from an ASP.NET Hidden Field. In my ASP.NET and JavaScript code, I have defined a Hidde ...

The MaterialUI FormControl API TextField is experiencing an issue where the onClick event does not trigger on the initial click

I am currently working on a React application where I have integrated a MaterialUI Form Control API TextField. However, I am facing an issue with the Select tag as the onClick method is only firing after the first click. There are no hidden CSS properties ...

Can you tell me the locations of the src/js and build/js directories?

Just starting out and seeking guidance. I am currently working with Node v4.2.1 and Gulp 3.9.0 on a Windows 7 machine, following along with a tutorial to familiarize myself with the task runner Gulp. I'm attempting to concatenate tasks but I seem to ...

Download a JSON file from an angularjs client device

I'm in the process of adding offline functionality to a Cordova app I'm developing. I have a PHP file that retrieves a list of images as JSON, which I then save on the client device using the FILESYSTEM API. However, when I try to display the ima ...