[Vuejs]-Vue – Passing arrays as arguments

1👍

There is a misunderstanding what the function parameters do:

filterParesImpares: function (a2, a1, f) {
  return this.a2 = this.a1.filter(f)
},
  1. this.a2 = ... does not write to this.numeros, it literally tries to write this.a2.
  2. Similarly, this.a1.filter does not exist.

Either you supply the name of the data properties or their values.

Fix the .filter call

To fix your immediate problem, write a1.filter, so remove the this., because this.a1 does not exist.

Fix the function’s parameters

If you change your function to supply names (change the call to filterParesImpares('impares', 'numeros', getImpares)), you can use them like this:

filterParesImpares: function (a2, a1, f) {
  this[a2] = this[a1].filter(f);
  return this[a2];
},

Javascript object access:

The reason this works is because JavaScript allows access to object properties the normal way (object.something), as well as if the object was an array with strings as indexes (object['something']).
This makes it possible to put the name of an object property in a variable and access the respective object property.

And yes, this has nothing to do with Vue, this is a language feature of JavaScript.

See MDN about Object and properties

1👍

No need to pass the data properties as parameters in the event handler, just get access to them inside the method using this :

 <!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="app2">
    <button @click="filterParesImpares">Impares</button>

    <ul>
      <li v-for="impar in impares">{{impar}}</li>
    </ul>
  </div>

  <script>
    const vueCles = {
      data() {
        return {
          numeros: [1, 2, 3, 4, 5, 6],
          impares: [],
          pares: []
        }
      },

      methods: {
        filterParesImpares: function () {
          return this.impares = this.numeros.filter(this.getImpares)
        },

        getImpares: n => n % 2 !== 0
      }
    }


    const app2 = Vue.createApp(vueCles).mount("#app2")
  </script>
</body>

</html>

1👍

The problem is that the function filterParesImpares is trying to access component’s a1 and a2 with this – doesn’t exists.
In your component the only values you can get with this are: numeros, impares and pares.
To fix you problem, just remove the this from the function:

filterParesImpares: function (a2, a1, f) {
  // return this.a2 = this.a1.filter(f)
  return a2 = a1.filter(f)
}

Leave a comment