RichardMiracles
RichardMiracles

Reputation: 2152

Use indexOf method with Vuejs

I have a method in my vue js element:

_deleteDesign : function(dsn)
{
    //_deleteDesign
    var url = '{{ url('/fapi/designsTmp/') }}/'+dsn.design_id;
    axios.delete(url)
    .then(function(){ 
        this.$delete(this.creations, this.creations.indexOf(function(el){
            return el.design_id = dsn.design_id;
        }));
    })
    .catch(function(e){
        alert('error deleting design');
    })
    debugger;
}

In this method I am using the indexOf function of Javascript, but vuejs reports me this error in the Chrome debugger:

this.creations.indexOf is not a function

What's the problem?

Upvotes: 1

Views: 3037

Answers (2)

Goran
Goran

Reputation: 3410

"indexOf" method can only be executed on variables that are type "string" or "array" (which is actually type "object").

So in your particular case "this.creations" must be either array or string. The issue is that you somehow ended up with the case when "this.creations" is not one of those types.

One possible solution is to add

console.log(typeof this.creations)

and monitor the type of this variable.

Also as previous answer mentioned the issue is that "this" changed context. One solution for this is to make copy of this object: const self = this;

in the beggining of _deleteDesign function and to use "self" object instead of "this". Generally avoid using "this" object as much as possible.

Upvotes: 0

kaliatech
kaliatech

Reputation: 17867

The this context has changed in the promise then handler because of new function declaration. One way to fix, would be to use ES6 arrow function which keeps the existing this binding for code within the function:

       .then(() => { 
             this.$delete(this.creations, this.creations.indexOf(function(el){
                return el.design_id = dsn.design_id;
             }));
          })

Upvotes: 1

Related Questions