Brynn Bateman
Brynn Bateman

Reputation: 769

How do I use the vue-resource plugin to delete an object on demand?

Using the vue-resource plugin, it has an example like this:

new Vue({

    ready: function() {

      var resource = this.$resource('someItem{/id}');

      // delete item
      resource.delete({id: 1}).then(function (response) {
          // handle success
      }, function (response) {
          // handle error
      });

    }

})

I am somewhat confused that this is under the ready property since it suggests it runs and deletes something as soon as the component loads. How do I actually use that resource.delete function from clicking an element? For example, I have this:

<div @click="deleteReward(reward)" class="glyphicon glyphicon-trash pull-right"></div>

which is currently calling this:

 deleteReward(reward) {
        this.rewards.$remove(reward);
        this.$http.delete('api/reward/' + reward.id).then(function (response) {
            console.log('deleted ' + reward.name);
        });
    },

But my understanding is that I should somehow be able to call resource.delete instead and not have to specify the URL and method explicitly. Am I wrong in that assumption?

What I want is to do something like @click="reward.delete()" and have it know to call the resource.delete automatically and have resource.delete accept the reward object as a parameter.

Upvotes: 0

Views: 1874

Answers (1)

pespantelis
pespantelis

Reputation: 15382

You could try something like this:

new Vue({
  data: {
    resource: null
  },

  ready: function() {
    this.resource = this.$resource('api/reward{/id}')
  },

  methods: {
    deleteReward(reward) {
      this.resource.delete({id:reward.id}).then(function (response) {
        console.log('deleted ' + reward.name)
      })
    }
  }
})

And then:

<div @click="deleteReward(reward)"></div>

Upvotes: 1

Related Questions