Daniel Richter
Daniel Richter

Reputation: 858

Why data: Variable is reactive to a Variable in computed: property in Vue

It's possible that I'm doing something wrong, but I do not understand the following result. I get the product Array (sorted by name) from the server. Now I need the lowest and highest price for a price slider so that I'm using computed properties. After that, the complete product array is sorted by price and I can't understand why?

    data:
      products: []
      ...
      methods: {
        loadProducts() {
          ...
          this.products = response.data.elements; //array is sorted correct by name
        }
      },
      computed: 
        maxPriceCalc: function() {
          var products = this.products;
          if(productss.length > 0) {
            var maxPrice = productss.sort(compare); //at this point - this.products is sorted by price too
            return maxPrice[0].calculatedPrice.totalPrice;
          }
          function compare(a, b) {
            if (a.calculatedPrice.totalPrice > b.calculatedPrice.totalPrice)
                return -1;
            if (a.calculatedPrice.totalPrice < b.calculatedPrice.totalPrice)
                return 1;
            return 0;
          }
          ...

Maybe anyone has an idea to figure it out.

Thx for time and help.

Upvotes: 0

Views: 291

Answers (1)

Michal Lev&#253;
Michal Lev&#253;

Reputation: 37763

Two reasons in play here (nothing to do with Vue - just plain old JavaScript):

  1. Array is the type handled by reference so your local products variable is pointing to the same array as this.products
  2. Array.prototype.sort() sorts the array in-place (not creating new array)

The easy solution is to use the spread operator to create a new array. Instead of var products = this.products, use var products = [...this.products]. This will create a completely new array with the same elements as the original array...

Although as you need min and max value at the same time, it would be really much better to implement this computed prop without any sorting just by scanning the source array with forEach, computing both values at the same time, and returning a simple object like this { minPrice: xx, maxPrice: yy }

Upvotes: 3

Related Questions