0

How can I access a property from a method inside another method in VUEJS? In this example, I need an "mb_id" from fetchMA method in order to use it in fetchMB args.

export default {
      name: 'details',
      data () {
         return {
            mA: {},
            mB: ''
         }
      },
      methods: {
         fetchMA(id){
            this.$http.get('apiurl/' + id )
            .then(function(response){
               this.mA = response.body;
            });
         },
         fetchMB(id){
            this.$http.get('apiurl/' + id )
            .then(function(response){
               this.mB = response.body;
            });
         }
      },
      created: function(){
         this.fetchMA(this.$route.params.id);
         this.fetchMB(this.mA.mb_id);
      }
   }

If I hard code a digit inside the created, such as - this.fetchMB(10); this fetches what I need, but for obvious reasons this is not feasible.

Thank you all,

-S

2
  • Is mA an array or an object that has an mb_id property? Commented Nov 3, 2017 at 16:28
  • @Bert an object, just a typo. fixed. Commented Nov 3, 2017 at 16:38

1 Answer 1

2

Returning the promise from fetchMA() will allow you to call then() on it so you can wait until this.mA has been set.

fetchMA(id){
    return this.$http.get('apiurl/' + id )
    .then(function(response){
        this.mA = response.body;
    });
},

You can then use it like this in created:

this.fetchMA(id)
.then(() => {
    this.fetchMB(this.mA.mb_id);    
})

It's not really clear what this.mA is from your example. You are declaring it like an array, but accessing it like an object.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, worked. I missed the return call inside the fetchMA method. Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.