Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing props in axios to Vue.js?

I want to pass props from a parent component to a child component. My prop is tid.

This is the parent component:

<div id="tracksec" class="panel-collapse collapse">
    <library :tid="track.category_id"></library>
</div>

This is the child component:

<script>
import Chapter from "./chapter";
import Http from "../../services/http/httpService";
export default {
    components: {Chapter},
    props:['tid'],
    name: "library",
    data(){
        return{
            library:{},
        }
    },
    computed:{
      getPr(){
          return this.$props;
      }
    },
        mounted(){
      console.log(this.$props);
        Http.get('/api/interactive/lib/' + this.tid)
            .then(response => this.library = response.data)
            .catch(error => console.log(error.response.data))
    }
}

This is the http source:

import axios from 'axios';


class httpService {

static get(url, params) {
    if (!params) {
        return axios.get(url);
    }
    return axios.get(url, {
        params: params
    });
}

static post(url, params) {
    return axios.post(url, params);
}
}

export default httpService;

I want to pass the tid value to the http.get function. For example:

Http.get('/api/interactive/lib/' + this.tid)

However the tid value is undefined. How do I get tid in the mounted or created hook?

like image 579
MohNj Avatar asked Dec 18 '17 14:12

MohNj


1 Answers

I'm new to Vue, but I think you might want to add a "watcher" that triggers on change. Your "track-object" is empty on create, this leading track.category_id being undefined. Then when you get an answer from your HTTP get, your value is set, but not updated in the library component.

Something like this:

<script>
import Chapter from "./chapter";
import Http from "../../services/http/httpService";
export default {
    components: {Chapter},
    props:['tid'],
    name: "library",
    data(){
        return{
            library:{},
        }
    },
    watch: {
        // if tid is updated, this will trigger... I Think :-D
        tid: function (value) {
          console.log(value);
            Http.get('/api/interactive/lib/' + value)
            .then(response => this.library = response.data)
            .catch(error => console.log(error.response.data))
        }
      },
    computed:{
      getPr(){
          return this.$props;
      }
    },
        mounted(){
      console.log(this.$props);

      // Will be undefined
      /*
        Http.get('/api/interactive/lib/' + this.tid)
            .then(response => this.library = response.data)
            .catch(error => console.log(error.response.data))*/
    }
}
</script>

Documentation about watchers

(Cant test the code, but you might get the idea)

like image 93
DannyThunder Avatar answered Sep 25 '22 10:09

DannyThunder