Vue organically expands an object into computed properties

Within my component, I am working with an array of objects named config, along with a property called currentIdx. As I was going through my code, I came across the need to do the following:

computed: {
    textStyle: function() {
        return this.config[this.currentIdx].textStyle;
    },
    text: function() {
        return this.config[this.currentIdx].text;
    },
    key: function() {
        return this.config[this.currentIdx].key;
    }
}

I experimented with replacing all these functions using:

computed: {
    ...this.config[this.currentIdx]
}

Although it compiled successfully, I encountered an error in the browser console. My analysis revealed that the issue lies in how computed requires functions, while the spread syntax (...) outputs objects. This brings me to the question: Is there a more efficient way to minimize repetition in this scenario?

Thank you for your insights!

Answer №1

Values that are computed have the ability to return objects, but they must be explicitly returned by the function. If this is not what you had in mind, feel free to let me know so I can offer further assistance!

let vm = new Vue({
  el : "#root",
  data : {
    current : 0,
    arrs : [
      {
        color : "background-color: blue;",
        text : "Dabodee Dabodai"
      },
      {
        color : "background-color: red;",
        text : "Angry"
      },
      {
        color : "background-color: green;",
        text : "See it works!"
      }
    ]
  },
  computed : {
    currentObject : function() {
      return this.arrs[this.current];
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="root">
  <input type="number" v-model="current" min="0" max="2">
  <p :style="currentObject.color">
    {{ currentObject.text }}
  </p>
</div>

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

A Guide to Handling Errors while Converting a Map to a Promise in Typescript

I am attempting to capture errors if any of the asynchronous code within my map function fails. It seems to enter the error block but does not log anything, as the error variable remains null. Is there an alternative method for handling errors within map ...

Prevent submission until all form fields are filled with data

I need help fixing the issue I'm having with disabling the submit button until all input fields have some data. Currently, the button is disabled but remains that way even after all inputs are filled in. What could be causing this problem? $(docume ...

Troubleshooting the 'npm ERR! ERESOLVE could not resolve' and 'peer dependency' issues: A guide to fixing the ERESOLVE error in npm

After several days of encountering an error while trying to set up a website for remote training, I have not been able to find a solution that fits my needs. Requesting your help to resolve the issue and get the site live on Vercel. Thank you in advance f ...

Is there a way to retrieve the previous URL using JavaScript?

Is there a way to retrieve the previous URL in a Next.js project? I came across this, but it always returns the base URL (http://localhost:3000/) when using document.referrer. Another approach I tried was pushing a state into window.history based on the of ...

The characteristics of angular js Service/Factory and how they influence functionality

I'm seeking clarification on the behavior of AngularJS, especially in terms of JavaScript. In my code, I have a controller that has an Angular factory injected into it. Here's a snippet from the controller: $scope.localObjCollection = myObjFac ...

Refresh the jQuery Carousel when the window is resized to switch the orientation from vertical to horizontal

I am in the process of creating a gallery for a responsive layout, utilizing jQuery Riding Carousels for the thumbnails. You can find more information about it here. One issue I am encountering is that when the window size shrinks to be smaller than 1024p ...

Issue with Trix text editor not triggering the change event

Lately, I've been facing some difficulties in getting the tirx-change event to trigger when there are changes in the content of a trix-editor. Despite using React JS for the view, I haven't been able to identify the problem. Below is the code sni ...

Choose a particular optgroup simultaneously using custom JavaScript

Check out this Fiddle for an example I am facing a situation where I have two different types of option groups with options. My challenge is to ensure validation between these two groups. How can I achieve this? Situation 1 If I select something from g ...

Nuxt 3: Leveraging SSR for Client-Side Data Refetching with useFetch

My current project involves building a simple SSR site with the help of useFetch. Everything runs smoothly when I hardcode the URL, but once I switch to using a runtime config variable (from the .env file), the fetch operation works on the server side with ...

jquery logic for iterating through all elements in a select menu encountering issues

In search of a solution to iterate through all options in a dropdown list using code, comparing each to a variable. When a match is found, I aim to set that particular value as the selected item in the dropdown and then exit the loop. Here's what I&ap ...

Retrieve information and update state right before component display in React Native

Consider this scenario: I have a modal that displays data from its state, which is an array. The state is set in the componentDidMount() function as recommended in the documentation. My goal is to display updated data every time the modal opens. I was able ...

The React MUI Tab component triggers a re-render and clears the states of its child components

In our endeavor to create a Tab Page using React MUI, we aim for each Tab to contain a child component. While there are no issues when adding these child components individually to a page without tabs, problems arise when incorporating them within the Tab ...

Install VueJs and its dependencies using npm within a Laravel project

I recently set up a new instance of Laravel on my system, and I made sure to uninstall and reinstall the latest versions of both nodejs and npm. Despite following all the steps, I'm still encountering issues with running npm install and npm run dev. C ...

JavaScript Thumbnail Slider Builder

I've been working hard on developing a custom JavaScript thumbnail slider that uses data-src. Everything seems to be in order, except the next and previous buttons are not functioning properly. Any assistance would be greatly appreciated. Here's ...

managing browser pop-ups in selenium with the help of JavaScript

My objective is to input a username and password in the popup box that shows up every time the page loads. I am utilizing selenium for this purpose, and unfortunately, all attempts I've made so far have been unsuccessful. I attempted to use the follo ...

Creating responsive tabs that transition into a drop-down menu for mobile devices is a useful feature for

I am looking to create a responsive tab design that drops down like the example shown below: Desktop/Large Screen View https://i.stack.imgur.com/hiCYz.png Mobile View https://i.stack.imgur.com/gRxLv.png I have written some code for this, but I am unsure ...

Transforming a canvas element into an image sans the use of toDataURL or toBlob

Recently, I developed a small tool which involves adding a canvas element to the DOM. Strangely, when trying to use toBlob or toDataURL, I encountered an issue with the canvas being tainted and received the error message (specifically in chromium): Uncaugh ...

Problem selecting a specific item within a dropdown menu

Currently, I am exploring Element UI, a visually appealing VueJS framework for user interfaces. One issue I have encountered is when placing a select element inside a dropdown menu, as selecting an item in the select element automatically closes the dropdo ...

I am struggling with sending post requests in Node.js

I am currently facing a challenge with handling form data from a webpage using Node.js and writing that data to a file. It seems like there might be an issue with how Node.js is processing my POST request, or perhaps the way I am sending the request from t ...

Having trouble creating a unit test for exporting to CSV in Angular

Attempting to create a unit test case for the export-to-csv library within an Angular project. Encountering an error where generateCsv is not being called. Despite seeing the code executed in the coverage report, the function is not triggered. Below is the ...