Incorporate a Vue.js computed property into the data retrieved from a server

Coming from Knockout.js, where observables are easily created by defining them, I'm curious if there's a similar approach in Vue.js.

let vm = {
    someOtherVar: ko.observable(7),
    entries: ko.observableArray()
};

function addServerDataToEntries(data) {
    data.myComputed = ko.pureComputed(() => vm.someOtherVar() + data.bla);
    vm.entries.push(data);
}

addServerDataToEntries({ bla: 1 });

In my current Vue.js project, I am fetching a list of objects from the server. For each object in the list, I need to add a computed property that can be used in a v-if binding. How can I go about achieving this in Vue.js?

Answer №1

The method used by Knockout is not familiar to me, but it seems similar to a Vue computed property. To implement this in Vue, start by creating a data object to store the fetched data:

data() {
  return {
    items: null
  }
}

Assuming you fetch the data in the created hook (or through Vuex):

async created() {
  const response = await axios.get(...);
  this.items = response.data;
}

Next, define your computed property:

computed: {
  itemsFormatted() {
    if (!this.items) return null;
    return this.items.map(item => {
      // Perform operations on each item here
    });
  }
}

Check out this demo that demonstrates using this approach to load and filter data. Feel free to let me know if this wasn't what you were looking for. (The original fetched data can be viewed in the console.)

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

Is it possible to incorporate custom scripts into the <head> section of the index.html file in Docusaurus?

I decided to organize my code by creating a scripts folder within the static directory. Inside this folder, I added a custom JavaScript file named "GetLocation.js". The path to this file is project/website/static/scripts/GetLocation.js Upon looking into s ...

How to pass dynamic data from a parent component to a child component in Vue.js

Having some trouble with authentication in my Vue view and component. When a user enters their username and password, then clicks the login button, the information is emitted to the parent component. The parent component then makes a fetch request to an A ...

Navigating through complex immutable entities

I am having trouble working with multidimensional immutable arrays. I would like to make my array immutable, but I'm not sure how to do so. Consider the following data structure: // data { // item { name: someName, todos: [ ...

Incorporate Vue JS Router for seamless redirection and page reloads

Recently, I encountered an issue with my Vue 3 app that consists of Login.vue and Home.vue files. After converting an admin HTML website to this Vue application, I noticed that my JavaScript functions only function properly after a page reload. Upon sett ...

Learn how to retrieve the HTTP headers of a request using AngularJS

When working with AngularJS, I know that accessing an HTTP request's GET parameters is easy using: $location.search().parameterOfInterest But how can I access the HTTP headers of the request? It's worth noting that I'm not utilizing $http ...

Assigning a specific data type value to an element as it enters the top of the viewport

I have a unique color code stored for each section, and when a section reaches the top of the screen (specifically -180px for the header), I want to dynamically change the text color of the header element as you scroll through the sections. Despite no erro ...

Filter through the array using the cast method

Trying to implement this: let selections = list.filter(obj => obj.type === "myType"); An issue arises with the filter function displaying an error message which states 'filter' does not exist on type 'NodeType' I attempted to ...

React Native - Invariant Violation: Objects cannot be used as a React Child (Utilizing Node.js for the backend)

Trying to calculate the total sum of orders and their quantity using Node JS on the backend. However, encountering issues with the fetch functions not working properly or missing something unknown. The API works as expected when tested in Postman, but err ...

Creating dynamic selection options in an HTML select tag using PHP

When retrieving category and sub-category information from an API json file, the API returns category objects with a "parent" attribute. Main category objects have a parent attribute equal to 0, and sub-category objects have the parent attribute equal to t ...

What is the reason for webpack searching for jQuery even though it is not necessary for the module?

Before I proceed with my question, I want to clarify that I may not fully grasp the intricacies of this issue and I apologize if it does not meet the standards of Stackoverflow's Q&A. Currently, we are facing a challenge in our project while tryi ...

What is the best way to handle multiple responses in Ajax within a single function?

Here is a simple code snippet: $.ajax({ url:'action.php', method: 'POST', data:{getcart:1}, success:function(response){ $('#getcart').html(response);//want to ...

How to selectively display specific columns when outputting JSON to a dynamic HTML table?

I'm looking to output specific JSON data in an HTML table with JavaScript. The headers will remain the same, but the JSON content will vary. Currently, I have a working function that generates the entire table using JavaScript: <body> ...

Creating individual product pages from an array of objects: A step-by-step guide

Is there a way in Next.js to create individual pages for each object in an array with unique URLs? Here is the input array: Input Array const products = [ { url: "item-1", id: 1, name: "Item 1", description: "lor ...

State is causing a conflict by allowing multiple menus to open when mapping over Menu objects

I am currently encountering an issue with my Material UI <Menu>. The problem arises when I attempt to display some data and interface functionality by mapping over a <Card>, along with adding an <IconButton> on each card that opens a menu ...

How can you optimize the storage of keys in JS objects?

Just pondering over this scenario: Consider a line definition like the one below, where start and end are both points. let ln = { s: {x:0, y:0}, e: {x:0, y:0}, o: 'vertical' } Now imagine having a vast array of lines, how can we sav ...

Arrange a collection of words in alphabetical order based on word importance

Given the array below [ { name: '4K UHD', commentator: 'Ali' }, { name: 'English 1 HD', commentator: 'Ahmed' }, { name: 'English 3 HD', commentator: 'Ahmed' }, { name: 'Premium 1 HD&a ...

Is it possible to attach a Vue component to more than one div element simultaneously?

import Selector from '@components/contactSelector' let vueInstance = new Vue({ components: { Selector }, data () { return { url: url, isFilter: false, type: 'external', selectedList: [] } }, rende ...

Vue.js error 8:3 error: Parsing error - Unforeseen usage of 'new' keyword

I am facing an issue with my Vuex store error: 8:3 error Parsing error: Unexpected keyword 'new'. // Encountering a problem with the Vuex store import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export ...

Utilizing reference memory to enable communication between two controllers

Within my Angular application, I have implemented a service to facilitate communication between 2 controllers and allow them to share the input variable from the search box. I am using kickSearch.box to reference memory...obj.property. However, there seem ...

Avoid shifting focus to each form control when the tab key is activated

I have a form where users need to be able to delete and add items using the keyboard. Typically, users use the tab key to move focus from one element to another. However, when pressing the tab key in this form, the focus only shifts to textboxes and not t ...