What is the conventional method for incorporating style elements into Vue.js components?

Imagine I have a Vue component with data retrieved from an external API, containing information about various books:

data: () => ({
    books: [
        {name: 'The Voyage of the Beagle', author: 'Charles Darwin'},
        {name: 'Metamorphoses', author: 'Ovid'},
        {name: 'The Interpretation of Dreams', author: 'Sigmund Freud'},
    ],
}),

I want to add presentation variables for each book, such as determining if a book is open or not. These variables should not be included in the API response to avoid cluttering it with presentation data.

Is there a conventional method in Vue to achieve this?

Answer №1

Once you have received the information from the API, you can incorporate the presentation data:

...
data: () => ({ books: [] });
...
methods: {
  // Call the API to retrieve the books
  async requestBooks() {
    // TODO: Implement try catch block
    const books = await getBooks(); // Your API call
    this.books = addPresentationInformation(books);
  },
  addPresentationInformation(books) {
    return books.map(book => {
      return {
        ...book, // Default format from API (name, author)
        open: false, // Include the open variable in the object
        reading: false,
        currentPage: 0
      }
    });
  }
},
created() {
  this.requestBooks(); // Invoke the API call in the created hook to initialize the books data prop
}

You have the flexibility to add multiple presentation variables as needed. It is advisable to utilize vuex for storing the books and their related presentation variables. This enables you to persist information in local storage for each book, allowing you to track whether a certain book is currently being read or is open even after restarting the application.

Answer №2

In my opinion, it would be beneficial to keep a separate array that holds specific information related to each book instead of directly altering the API response data. This approach works better for me personally.

Answer №3

One alternative approach could be to duplicate the object, make modifications to it, and preserve the original response data.

data(){
    let newData = Object.assign({}, this);
    // include any required presentation changes
    return newData;
}

Answer №4

My current approach involves utilizing the normalizr library to handle and streamline responses obtained from the backend API. This tool enables me to incorporate additional data as needed. As an illustration, the code snippet below showcases how the schema is configured to include the hidden attribute within the response.

const taskSchema = new schema.Entity(
    'tasks',
    {},
    {
        // Add supplementary data for presentation
        processStrategy: (value) => ({
            ...value,
            hidden: false
        }),
    }
);

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

Expanding an array in JavaScript

I need assistance with... let a = ['a', 2, 3]; a += function(){return 'abc'}; console.log(a[3]); Therefore, I am looking for a shorthand method to push() in array with the above content. Does anyone know of an operator that can help ...

Having trouble validating the input file in Laravel?

I am encountering an issue with validating a file input. The validation process consistently returns The given data was invalid., even when the provided file meets all of the validation criteria. It's worth noting that I am uploading multiple files si ...

How can I ensure that Redux-saga waits for API calls to resolve instead of returning promises continuously? Is there a way to make "yield call" wait for API calls to complete?

Where I'm initiating the API request: function fetchCharacter(value){ return axios.get(`https://www.breakingbadapi.com/api/characters?name=${value}`) .then(res=>{ console.log(res.data) }) .cat ...

Caution: Potential Unresolved Promise Rejection Detected (ID: 21) - Error: Undefined is not a valid object when trying to evaluate 'res.json'

ERROR Getting an Unhandled Promise Rejection (id: 21): TypeError: undefined is not an object (evaluating 'res.json'). Any suggestions on fixing this issue in my code? I've checked the logs for user and loggeduserobj, and they seem to be cor ...

Changing a value within a JSON object

I need to update the "Last" Price for MarketName USDT-BTC. How can I change the value from 16750.00000001 to 17000.00000001 and then transmit it through my API? { "success":true, "message":"", "result":[{ "MarketName":"USDT-BTC", "High":16 ...

Trouble with hide/show loop in setTimeout function

I have a special animation with 3 text items that are initially invisible. The goal is to make these items appear one by one with a delay of 2 seconds after clicking a button. Each item should be visible for 1 second before fading out and making way for th ...

Eliminate the classes that were inserted through Jquery

I'm currently working on an accordion and I've encountered an issue with jQuery adding classes that I don't want. How can I prevent jQuery from adding certain classes? The code below is what I have, but for some reason, jQuery keeps adding t ...

Place the item at the top of the list before scrolling downwards

I'm struggling with what seems like it should be a simple task. My goal is to add new items to the top of a list and have the list scroll down to show the new item. So far, I've managed to create and add a new list item using this code snippet: ...

Error: 'err' has not been defined

Recently, I embarked on creating my very first API using Mongo, Express and Node. As I attempted to establish an API endpoint for a specific user, the console threw me this error: ReferenceError: err is not defined. Curiously, the same method worked flawle ...

Exploring the World of jQuery Caching and Navigating Through Objects

I'm interested in learning more about jQuery caching and how it can enhance performance. Can you explain how to properly utilize this technique? From what I understand, when using a jQuery selector, you're essentially searching the DOM to create ...

Encountering an issue where the Angular build is unable to locate the installed Font-Awesome node module

Every time I attempt to compile my project using ng build --prod, I encounter the following error: ERROR in ./src/styles.scss Module build failed: ModuleBuildError: Module build failed: Error: Can't resolve '~font-awesome/css/font-awesom ...

Issue with Angular: event.key doesn't register as shft+tab when pressing Shift+Tab key

Our website features a dropdown menu that can be opened and closed by clicking, revealing a list of li items. However, we are currently experiencing an issue with keyboard focus navigation. When the Tab key is pressed, the focus properly moves from one li ...

JQuery syntax for adding a comma before the first element in an array

When I insert data into an array, the output in my console includes a comma before the first element (9). How can I remove this comma from the first element using the provided code snippet? ,9,My firstname,My lastname,<a href="/cdn-cgi/l/email-protecti ...

Discover and eliminate the style attribute through a click action

I've been struggling to find a solution to remove the style attribute from a specific tr tag within a table when it is clicked. I've tried several lines of code but none seem to work. Here's the link to the fiddle for reference: http://jsfi ...

Invoking a plugin method in jQuery within a callback function

Utilizing a boilerplate plugin design, my code structure resembles this: ;(function ( $, window, document, undefined ) { var pluginName = "test", defaults = {}; function test( element, options ) { this.init(); } test.pro ...

The function successfully triggers when clicked using (React, JS, TS) but does not respond to key presses

When the function is called with "onClick", it works correctly, but when called with "onKeyPress", it does not execute an if statement. scenario Consider a scenario where you can search for food recipes (e.g. "pizza") and receive a list of recipes from a ...

Steps for implementing a JavaScript script to modify all values within a table

I am facing an issue where I need certain "td" elements to disappear when the date associated with them has passed. However, currently only the first column is affected while others remain untouched. <script type="text/javascript"> //<![CDAT ...

Challenge encountered with AJAX request

Whenever I trigger an AJAX request to a JSP using a dropdown menu, it works perfectly fine. However, when I try to trigger the same request using a submit button, the content vanishes and the page refreshes. function najax() { $.ajax({ url:"te ...

Attempting to Send an Ajax Request and Utilize the Result within a React Component

I am having issues with my tweet box component. I have a submit function that triggers the getAllTweets function when called. The problem is that I am unable to capture the value of the field and pass it on to the getAllTweets function in order to create ...

The system has encountered an issue: "EntityMetadataNotFound: Unable to locate metadata for the entity named 'User

Just wanted to reach out as I've been encountering an issue with my ExpressJS app recently. A few days ago, everything was running smoothly without any errors. However, now I'm getting a frustrating EntityMetadataNotFound: No metadata for "User" ...