"Mastering the art of leveraging computed properties in Vuejs to efficiently view nested arrays

I created a Vuejs component as shown here.
My objective is to access the value inside the filteredShoes method of the watch feature.

   data():{
       coor: [
              { "name": '',
                "shoes": '' },
              { "name": '',
                "shoes": '' }       
             ]
   },

   computed {
      filteredAny(){
        return this.coor.filter(it=>['shoes','name'].includes(it));
      },
      filteredShoes(){
        return this.coor.filter(it=>it === 'shoes');
      },
     filteredName(){
        return this.coor.filter(it=>it === 'name');
      }

    }

    watch {
      filteredShoes(){
        console.log('The shoes have been updated');
      }

    }

So I attempted the following, but it returned an error indicating val is undefined.
I am hoping that 'val' reflects the values in 'coor' from the data section.
How can I resolve this issue? Thank you for taking the time to read.

 
watch {
      filteredShoes(val){  
        for(let i=0; i < val.length; i+=1){} 
      }

    }

Answer №1

Given that this.coor is an array consisting of objects, the variable it will be assigned as an object. This means that it != 'shoes', resulting in an empty array being returned by your filter function.

If you are utilizing a computed method called filteredShoes() in this manner:

<div v-for="shoe in filteredShoes"> ... </div>

You can simply rely on the computed property without necessitating the use of a watcher. Whenever elements are added or removed from the array, the computed property will execute. However, modifications to the properties within an object of the array will not trigger the computed property.

I am uncertain about the specific structure of your this.coor object, so I assume the following for demonstration:

coor: [
   { "name": 'Model 1', "shoes": 'Nike' },
   { "name": 'Model 2', "shoes": 'Reebok' }       
]
...
computed {
   filteredShoes(){
      let shoes = this.coor.filter(item => item.shoes === 'Nike');

      for(let i = 0; i < shoes.length; i++){ ... } // assuming you're updating each object here

      return shoes; // returning an array for HTML looping
   },
}

To filter based on type, consider restructuring your coor object like so:

coor: [
   { "name": 'Model 1', "type": 'shoe' },
   { "name": 'Model 2', "type": 'shoe' }       
]
...
computed {
   filteredShoes(){
      let shoes = this.coor.filter(item => item.type === 'shoe');

      ...
      return shoes; // returning an array for HTML looping
   },
}

Answer №2

For those looking to do deep computations within an array, this code snippet below may be helpful:

  computed: {
    computedArray: {
      cache: false,
      get() {
        return this.sourceArray;
      },
    },
  },

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

Tips for setting a default checked radio button in Vuejs

Upon page load, the radio button status should initially be checked. Then, when the radio button is changed, a div below it should hide and show accordingly. I have attempted to write the code for this functionality, but unfortunately it is not working a ...

Tips for converting a select option into a button

Currently, I am working with Laravel to develop my shopping cart. My goal is to implement a feature that allows customers to select the quantity of a product and have the price update accordingly when they click on a specific number. However, I am facing a ...

Every time I load the script, my global variables reset. How can I prevent this constant refreshing?

As I work on completing a prototype for my system, I am facing an issue with global variables reinitializing every time the script reloads. Currently, I am not using localStorage and simply need a quick solution to prevent the variables and functions from ...

The persistent issue of the modal box disappearing persists, despite my efforts to remove additional instances of bootstrap.min

I have been struggling to prevent my modal box from disappearing, despite trying various solutions found online. How can I ensure that it stays visible? Here is the code in question: <html> <head> <title> Test Slides </titl ...

Does this function only function on a singular div?

I need some help! I'm having trouble getting a function to trigger on the divs below the initial one. Any advice? ...

Select any menu option to return to the one-page layout and then scroll down to find the location

I'm wondering if there is a way to navigate back from an external page to a specific section on my one-page website with a fixed menu? On my one-pager website, I have a fixed menu that includes a "apply for a job" button. When clicked, it takes users ...

How can we enhance our proxyURL in Kendo UI with request parameters?

As outlined in the Kendo UI API documentation, when using pdf.proxyURL with kendo.ui.Grid, a request will be sent containing the following parameters: contentType: Specifies the MIME type of the file base64: Contains the base-64 encoded file content fil ...

Working with SASS imports in an isomorphic React app: best practices

Currently, my React app is set up with SSR support as follows: React app Express server that compiles the React app using webpack Using babel-node to run the Express app with ES6 features Everything works fine until I added CSS modules to the React app, ...

Activate trust proxy in Next.js

When working with Express.js, the following code snippet enables trust in proxies: // see https://expressjs.com/en/guide/behind-proxies.html app.set('trust proxy', 1); I am attempting to implement a ratelimit using an Express middleware that is ...

Issue with JavaScript JSON.parse converting string values to Infinity

Does anyone have an explanation for this peculiar behavior I encountered while using the JSON.parse() function in Javascript? Normally, when you pass a string to it, it should generate an error. For example, JSON.parse("5ffc58ed1662010012d45b30" ...

Nuxt/Buefy may sometimes require a page refresh in order for CSS to properly load

Recently I started using Nuxt js and encountered a CSS issue when transitioning between pages. Whenever I navigate from one page to another in my application, the Buefy CSS fails to load properly. https://i.sstatic.net/yq4Qx.png If I manually refresh th ...

Ending <div> tag dependent on condition in Vue.js

Having trouble with a conditional tag ending, can't seem to get it to work. Any suggestions for a workaround? <div class="container"> <template v-if="smallScreen"> </div> </template> <template v ...

Is there a way to set a fixed value for properties in Three.js?

I am on the hunt for the equivalent in Three.js to vertexAttrib. My goal is to assign a fixed value to my shader attribute. ...

What is preventing Facebook from merging its CSS/JS files together?

I wonder about the reasoning behind Facebook developers' decision not to consolidate their scripts and stylesheets into single files, opting instead to load them on demand through their CDN. Considering the complexity of Facebook as an application, I ...

Is it possible to recycle lights in three js?

Do I need to set up three JS lights every time I load a 3D model? In programs like Maya, lighting and camera configurations are often set up during rendering. Is there a way to export this as part of an OBJ file? If we can reuse the same lighting setup, o ...

Transitioning one element's opacity to zero while concurrently increasing another element's opacity to replace it

There are a total of 3 div elements and 3 links included in this setup. The goal is to only display one div at any given time. Upon clicking on a link corresponding to a different div, the current one should fade out while the selected one fades in seamle ...

What is the best way to output a variable that is returned by a function?

Here is a function I have: function findAddressViaGoogle(address){ var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': address }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { ...

What is the best way to create a point within a mesh?

I have several meshes and I'd like to insert a point randomly within the confines of hexagon[0]. How can this be achieved? var Hexagon=new Array(); Hexagon[0] = new THREE.Mesh( HexagonExtrude[0],material[0] ); Hexagon[1] = new THREE.Mesh( HexagonExtr ...

Utilizing Vue.js to activate click events from a specific class

My current project involves the use of vuejs. I am trying to create a method that will be triggered whenever an element with a specific class is clicked. Unfortunately, I'm experiencing some difficulties in setting this up in vuejs, even though I had ...

Creating a Form Layout with Bootstrap - Organizing Text Boxes and Text Areas

https://i.sstatic.net/oqRwR.jpg In the image above, I need to adjust the position of the textbox to align it with the TextArea. Is there a Bootstrap class that can help me achieve this? My current version of Bootstrap is 3.3.6. HTML &l ...