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

Can you import folders containing *.vue files in your project?

Repeating code is my least favorite thing. Currently, I am importing vue files in a repetitive manner in my main.js file. import Default from '../../src/components/default.vue'; import Home from '../../src/components/home.vue&apo ...

Clicking outside of a focused div does not trigger a jQuery function

Check out this HTML snippet: $html .= " <td><div class='edit_course' data-id='{$id}' data-type='_title' contenteditable='true'>{$obj->title}</div></td>"; Next, see the jQuery code below: ...

unable to retrieve the value of this.table property within a JavaScript class

In my JavaScript code, I have created a class that generates a MySQL model like so: class Model { constructor(options = {}, table) { this.options = options; this.table = table; this.create(); } create() { let queryString = `INSERT INT ...

I have a quick question: What is the most effective method for creating PDF templates with Angular and .NET 6, specifically for designs that feature heavy

Seeking the optimal solution for creating PDF templates using Angular and .NET 6? Specifically looking to design templates that heavily feature tables. In my exploration of efficient PDF template creation with Angular and .NET 6, I ventured into using pdf ...

Obtain image file paths dynamically in a folder using Nuxt

Incorporating nuxt with vuetify, I have successfully implemented a carousel component. Now, my goal is to generate a list of the .png files located in the static folder. By referencing a tutorial on dynamically importing images from a directory using webpa ...

Filtering data from MongoDB within the controller logic

I have a query in my controller that retrieves records from a MongoDB document. However, I need to filter the incoming records by a field archived == true. The current code works fine without any filters. I'm trying to figure out where to add the fil ...

Are you experiencing difficulty loading ng-view in AngularJs?

I am new to AngularJs. I am currently using a wamp server and have successfully loaded the HTML page, but unfortunately the view is not being displayed. I have added ng-app to the body as well, but still unable to load the view. <!DOCTYPE html> ...

Tips for interacting with a custom web component using Selenium WebDriver

As a newcomer to writing selenium tests, I am attempting to create an automated test for a carousel feature on our homepage. The objective is to click on one of the carousel navigation buttons and then confirm that a specific inline style has been applied ...

A comparison between the Composition API and traditional Plain JavaScript syntax

I'm currently exploring the necessity of utilizing the 'new' Vue Composition API. For instance, take the following component extracted from their basic example: <template> <button @click="increment"> Count is: {{ ...

Showing information in a table on a webpage using JavaScript and HTML

After running a console log, I am presented with the following data: 0: {smname: "thor", sim: "9976680249", pondo: "10"} 1: {smname: "asd", sim: "9999999999", pondo: "0"} 2: {smname: "asd", sim: "4444444444", pondo: "0"} 3: {smname: "bcvb", sim: "78678967 ...

The Json parsing failed to deserialize the API response

Struggling to send a JSON to my API, I've tried various solutions but still can't figure out what's going wrong. I'm stuck on this post call function: @PostMapping(path = "ts/sts") public void saveTestStep(@RequestBody Tes ...

Error: Syntax mishap detected - Oh dear

Recently, I've been developing a small slideshow / public display for a client using the HTML5 Rock's Slideshow code. Everything was going smoothly until I encountered a DOM Exception 12 - an error related to CSS selectors. Strangely, I couldn&ap ...

Ordering an Array of JavaScript Objects in a Custom Sequence (utilizing pre-existing methods)

Imagine we have an array of objects: ["c", "a", "b", "d"] Is there a way in ECMAScript or through a third-party JavaScript library to rearrange the objects in the first array to match the order specified by the second array, all within one line or functi ...

The sticky element should only be active when the visible section is overflowing vertically. There should be no scrollbar if the height is minimal

I'm currently working on a Whatsapp-style navigation bar and facing an issue with the sticky navbar functionality. https://i.stack.imgur.com/Cy3lA.gif Please refer to the details below for more information. To resolve this issue, I have included ...

What is the best way to save JavaScript array information in a database?

Currently working on developing an ecommerce website. My goal is to have two select tags, where the options in the second tag are dynamically populated based on the selection made in the first tag. For example, if "Electronics" is chosen in the first tag f ...

utilizing the .on method for dynamically inserted elements

I have a code snippet that triggers an AJAX request to another script and adds new <li> elements every time the "more" button is clicked. The code I am using is as follows: $(function(){ $('.more').on("click",function(){ var ID = $(th ...

From HTML to Python to Serial with WebIOPi

I am facing a dilemma and seeking help. Thank you in advance for any guidance! My project involves mounting a raspberry pi 2 b+ on an RC Crawler rover, utilizing WebIOPi for the task. However, I am encountering challenges and unable to find useful resourc ...

Mapping an HTTP object to a model

Currently facing an issue with mapping an http object to a specific model of mine, here is the scenario I am dealing with: MyObjController.ts class MyObjController { constructor ( private myObj:myObjService, private $sco ...

JQuery animations not functioning as expected

I've been attempting to create a functionality where list items can scroll up and down upon clicking a link. Unfortunately, I haven't been able to achieve the desired outcome. UPDATE: Included a JSFiddle jQuery Code: $(document).ready(function ...

Ensure that you patiently wait for the axios method to finish execution before moving on to the

I am currently learning vue.js and struggling with the concept of promises. I need to initialize a variable with data from an API call, but I want to ensure that the Axios call is generic: { data: { list: [], }, methods: { ShowList: function ...