Ways to prevent duplication when mounting and updating a Vue component

Working on a Vue application, I have various form components that can either create a new record or edit an existing one. When a form is active, clicking on another record or the create button should replace or clear the form's contents.

The issue arises from the repetition in setting up data properties and watch functions within my code.

For instance:

props: ["record"],
data() {
    return {
        name: this.record ? this.record.name : "",
        age: this.record ? this.record.age : null
    };
},
watch: {
    record(record) {
        this.name = record ? record.name : "";
        this.age = record ? record.age : null;
    }
}

I find it cumbersome to repeat the setup process in both the data function and the watch function for every property in the record object. This approach becomes error-prone as the number of properties grows.

Is there a way to consolidate this initialization logic into a single location and eliminate the redundancy?

Answer №1

In order to address the issue, you can include an immediate property within your watcher function to ensure it is called upon initialization as well. This will handle the initial value of the record property. See the code snippet below for implementation:

props: ["record"],
data() {
  return {
    name: "",
    age: null
   };
},
watch: {
  record: {
    immediate: true,
    handler(value) {
      this.name = this.record ? this.record.name : "";
      this.age = this.record ? this.record.age : null;
    }
  }
}

For more information, refer to: Vue's Official API Reference for vm.$watch

Answer №2

What do you think of this solution?

props: ["data"],
info() {
    return this.updateData(this.data, {});
},
monitor: {
    data(data) {
        this.updateData(data, this);
    }
},
updateData(what, where) {
    where.name = what ? what.name : "";
    where.age = what ? what.age : null;
    return where;
}

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

Triggering a Dialogflow Chat Window with a click on a Material-UI Floating Action Button in a ReactJS application

I have encountered an issue in my code where I am attempting to toggle the display of a Dialogflow Chat Window, <ChatWidget />, when a user clicks on the Material-UI Floating Action Button, <FloatingActionButton/>. The default state is set to f ...

Achieving a Subset Using Functional Programming

Looking for suggestions on implementing a function that takes an array A containing n elements and a number k as input. The function should return an array consisting of all subsets of size k from A, with each subset represented as an array. Please define ...

The dygraphs library is experiencing an issue due to a discrepancy between the number of labels and the number of

Having trouble with the dygraphs. I've extracted an array from PHP that appears like this: data = [ { "DATA": "2016-01-22", "TOTAL": [ "7", "4", "20", "0" ] }, { "DATA": "2016-01-25", "TOTAL": [ ...

Tips for creating ternary operator logic that account for numerous conditions and optional parameters:

Trying to create a logic for my validator functions that involves using objects as errorMaps for input validation. In the code snippet provided, args.drugName is an optional field. If the user provides text, we want to ensure it is greater than 3 letters; ...

What is the best way to display errors from a Node backend on a React frontend?

When making an API call, I am encountering multiple errors. My goal is to display relevant errors from the backend on the frontend. For example, I would like to indicate the error 'Site name exist' on the frontend. Backend: if (Sname) { cons ...

Placing a document.write statement inside the load function of a fresh Dashcode template prevents the generation of the remaining JavaScript code

I've been working on a new custom safari template using dashcode ("This template creates a blank web application, ready for customizing."). In the process, I noticed that it automatically generates a function called load in main.js that is then called ...

The hyperlinks on the webpage are not functioning

I am encountering an issue with a link on a particular page. When scrolling down, the link works perfectly; however, when I attempt to scroll up, it remains in the same position. Here is a snippet of the code: (function($){ /* Store the original positions ...

The error message "this.props.navigation" is not defined and cannot be evaluated as an object

Recently, I encountered an issue with my navigation system. Within my application, there are 3 screens or components that I navigate between using react-navigation. The first screen prompts the user to enter their mobile phone number and password, which is ...

Enhancing Filtering Capabilities with Multiple ng-Model in AngularJS

I am facing an issue with filtering a form based on user input in a text box or selection from a dropdown list. The text box filter works fine individually, but when I try to combine it with the dropdown list selection, neither filter seems to work. Below ...

Facing a NodeJS error about headers being set when I haven't actually set any

My middleware function checks if the user is logged in on every page load, as shown below: app.use(function(req, res, next) { if (req.cookies.hasOwnProperty('rememberToken')) { app.get('db').Users.find({'rememberToken': ...

What is the process of retrieving JSX within an object using a function that searches for data (in the form of JSX) in a separate

I am trying to extract JSX content from another file called categoriesDetails and store it in an object (foundCategory) by using the find function to check the item.title. Below is my implementation: This is how I am retrieving the data and intending to p ...

Set the rowspan to 2 when the v-for index does not equal 2

This is the table I am working with: <table class="table table-condensed table-sm table-striped table-bordered" id="list"> <thead> <tr> <th v-for="(column, index) in columns" :key=& ...

What prevents certain scenarios from being encapsulated within a try/catch block?

Just attempted to handle ENOENT by using a naive approach like this: try { res.sendFile(path); } catch (e) { if (e.code === 'ENOENT') { res.send('placeholder'); } else { throw e; } } Unfortunately, this method is ineffectiv ...

The issue of receiving a 404 error when attempting to send a string via Ajax

When a key is pressed and released, a JavaScript function is triggered. The function is supposed to call a controller action and return a result, but instead, I am receiving a 404 error. I have set breakpoints at the beginning of the controller action, but ...

Navigating through a 3D world with just the tilt of

I am currently developing an immersive VR web application using three.js. I have integrated the device orientation controls from the Google Cardboard three.js demo for camera navigation. Now, I am looking to incorporate keyboard controls for additional fu ...

What is the method to reach a named parameter within a function?

Currently, I am building a RESTful web service using Node JS in combination with Backbone JS. Within this service, there is a specific REST method called GET /users/id/:id, where :id represents the user's identification number. The purpose of this met ...

Developing a universally accessible variable for utilization in various functions

I'm having trouble understanding why 'currentPos.LatLng' is undefined when trying to access it outside the function even though it's part of an object. I want to be able to retrieve the current position values to use them in another fun ...

What is the reason for the code to execute without errors using the 'let' keyword, but encountering issues with the 'var' keyword?

Take a look at the code snippet below: <button id="btn-0">Button 1!</button> <button id="btn-1">Button 2!</button> <button id="btn-2">Button 3!</button> <button id="btn-3">Button 4!</button> <script type ...

`The server fails to retrieve parameters passed through an angularJS HTTP GET request,

In my controller.js file, I've come across the following block of code: $http({ method: 'GET', url: '/getGuestList', params: {exhibitorID: 1} }) The purpose of this code is to fetch all the guests belonging to a parti ...

How to make an element vanish in Vue.js after a transition

My webpage features a notification system created with vue.js. Everything is functioning properly, but I am looking to remove the element once the transition has completed. Currently, I am achieving this using a setTimeout function, which is not the most e ...