Is it more advantageous in Vue to pre-process and save data directly to the data property, or to utilize computed properties?

I am interested in hearing diverse perspectives on this topic. When working with Vue (and possibly other frameworks), is it more beneficial to prepare non-reactive data through a method and store it in the data for use in the template, or is it preferable to handle this preparation within computed properties?

For instance:

Consider a scenario where we have a page component and an imported modal component that showcases strings created from distinct arrays of strings. These strings are extracted from a single array of objects. The modal receives props related to these strings from the parent component. Once the modal is displayed, its data remains static, therefore reactivity in props is unnecessary.

There are two conflicting methodologies:

  • A) Establish a data object for modal props with some preset values. Upon clicking the button, iterate through the data array once, employ Set to generate an array of unique strings, assign the data, and then render the modal.
  • B) Create a computed property for each set. Each computed property iterates over the same array.

Highlighted below are code snippets exemplifying both approaches:

A)

{
  data: () => ({
    modalSettings: { names: '', codes: '' }
  }),
  methods: {
    handleClick () {
      const names = new Set()
      const codes = new Set()
      this.dataArray.forEach(({ name, code ) => {
        names.add(name)
        names.add(code)
      })
      this.modalSettings = { names, codes }
    }
  }
}

B)

computed: {
  names () {
    return this.dataArray.map(x => [...new Set(x.name)])
  },
  codes () {
     return this.dataArray.map(x => [...new Set(x.name)])
  }
}

In approach A, there is more code involved but only one iteration is needed. Despite having a function called first and then updating the data object for template usage, the data ends up existing in two different locations. Is this overly complex? Or would it be preferable to separate the actions performed by a function and result storage into an object?

On the contrary, approach B entails less code and consolidates everything in one place, but requires looping through the array for each property (should this matter?). Is consolidating all operations in a singular location more advantageous?

What makes one approach superior to the other? Is approach A more challenging to sustain and/or less scalable compared to approach B?

Answer №1

To ensure dynamic updates for your this.dataArray, opt for computed properties. With option A, you would have to monitor changes manually and invoke your method, resulting in more code without any performance benefits.

Even if this.dataArray remains constant, computed properties will only be calculated once.

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

Invoking Ajax within a for loop

for (var i = 0; i < 5; i++) { using (x = new XMLHttpRequest()) sendRequest("GET","d.php?id=" + i), checkResponse(null), updateStatus = function() { if (x.state == 4 && x.responseCode == 200) notifyUser(i); } } My goal now is to e ...

What could be causing the triggering of two AJAX requests in the given JavaScript code?

I have a code snippet that fetches data from the server. I want to trigger it on document.ready(). My expectation is that the first request is sent to the server, receives a response, and then the second request is made, and so forth. However, when I insp ...

Embed a script into an iframe from a separate domain

While experimenting, I attempted to inject a script inside an iframe element using the following method. However, since the child and parent elements do not belong to the same domain (and I am aware that XSS is prevented in modern browsers), I was wonder ...

Removing filters dynamically from ng-repeat in Angular

I am currently using ng-repeat to display a list of staff members: <div ng-repeat="user in staff | profAndDr"> There is also a custom filter called 'profAndDr' that only shows people with the titles "Dr." and "Prof.": app.filter('pr ...

What is the best way to prevent the dropdown function in a selectpicker (Bootstrap-Select)?

Is there a way to completely disable a selectpicker when a radio button is set to "No"? The current code I have only partially disables the selectpicker: $("#mySelect").prop("disabled", true); $(".selectpicker[data-id='mySelect']").addClas ...

Transfer information from an Express route to a function exported from a Node module

I'm new to using node.js and I've been told that I need to use middleware, but I'm having trouble understanding its purpose and the proper way to implement it. I have data that is being sent from my view to an express route. ROUTE - route.j ...

Implementing a toggle function in Vue.js to add or remove a class from the body element when a

I'd like to add a toggleable class to either the body element or the root element("#app") when the button inside the header component is clicked. Header.vue : <template lang="html"> <header> <button class="navbar-toggler navbar-tog ...

Should Bower and Grunt Be Installed Globally or Locally?

When it comes to installing packages globally, we typically avoid it due to the possibility of working on multiple projects simultaneously that require different versions of the same libraries. However, there seems to be conflicting information regarding t ...

Modifying object colors on hover using three.js

As a beginner in the world of Three.js and WebGL, my first project involves creating a model of an animal and animating it in different ways, such as having its head follow the mouse cursor. The model consists of various geometries that are combined in sep ...

What is the best method for fetching the values of a select element in React.js?

I'm struggling to retrieve the value of a selected element in a dropdown list. I've tried debugging it, but haven't been able to get the value. I attempted to console log e.target.value, but unfortunately, it didn't work. Any thoughts o ...

Is there a way to delete highlighted text without using execCommand and changing the font color

With my current use of JavaScript, I am able to highlight or bold a selected text range successfully. However, I am unsure how to undo the bold and unhighlight the text if the button is clicked again and the selected range is already bolded or highlighted. ...

What is the best way to efficiently load all of my web applications within the web application that I am currently developing?

https://i.stack.imgur.com/IAjIW.png Greetings! I am currently a novice Web Developer and here is my current situation: I am working on developing 3 web applications, with one additional application that will load all three of them. Please refer to the im ...

"Enhance Your Website with Bootstrap Modal and Jazz up Your

I am encountering an issue with modal-bootatrap and bootstrap-datepicker. Within the datatable, there is a button provided for editing. Upon clicking the edit button, a modal-bootstrap will be displayed. The modal-bootstrap contains a form for editing d ...

Make sure to clear the timeout in JavaScript before re-calling the function again

Scenario: Whenever a user clicks on a cell within the "#test" table, the "update_func" function will run and repeat every 10 seconds. If the user clicks on the same cell or another cell, multiple instances of "update_func" start running simultaneously ev ...

Uncover hidden content by clicking a button with JavaScript

I need help with creating a function that hides additional content until a button is clicked. Currently, my script displays the content by default. How can I modify it to hide the content by default and only reveal it when the button is clicked? functi ...

Is the template inheritance in Vue similar to the one in Symfony with Twig?

My goal is to define blocks within a Vue component's template, as shown below: {# templates/blog/layout.html.twig #} {% extends 'base.html.twig' %} {% block body %} <h1>Blog Application</h1> {% block content %}{% endbloc ...

Is there a way to block the .load() function directly from the browser console?

I am looking to enhance the user experience on my website by dynamically loading certain content after login. This involves using a $.post(...) method to interact with a servlet that verifies the user's credentials, followed by a $.load(url) function ...

Looping through ng-repeats, extracting checked checkbox values in Angular

I am currently dealing with multiple nested ng-repeats in my project, and the third level down consists of a group of checkboxes. Initially, I receive an array of options for these checkboxes, which I handle with the following code snippet: <div class= ...

Using JavaScript onChange event with ModelChoiceField arguments

In my Django project, I have a Students model with various fields. I created a ModelChoiceField form allowing users to select a record from the Students table via a dropdown. forms.py: class StudentChoiceField(forms.Form): students = forms.ModelChoic ...

What is the best way to arrange <div> elements with text inside without moving the text?

I need help figuring out how to stack one or more <div> elements on top of another <div> element while maintaining the text content within each. My issue is illustrated in this fiddle: https://jsfiddle.net/rd268ucy/1/. When attempting to drag o ...