0

Im using Laravel blade and Vue js 2. Im trying to perform a simple task: populate secondary select once first select being changed. With axios call of course. Here is HTML part:

<div class="content" id="app">
    <select v-model="selected" @change="onChange">
        <option value="" disabled selected>Please Select the Attraction</option>
    @foreach($pkgs as $pkg)
        <option value="{{$pkg->id}}">{{$pkg->name}}</option>
    @endforeach
    </select>
    <select v-model="selected2">
        <option v-for="subpackage in subpackages" v-bind:value="subpackage.id">@{{ subpackage.name }}</option> 
    </select>
</div>

Here is the js part:

new Vue({
    el: '#app',
    data: {
        selected: '',
        selected2: '',
        subpackages: [
            {id:'', name:'Please select an attraction first'}
        ]
    },
    methods: {
        onChange:function(){
            axios.get("{{route('pos.ajaxGetPkg')}}", {
                params:{
                    pkg_id: this.selected
                }
              })
            .then(function(response){
                this.subpackages = [];
                this.subpackages = response.data.variants;
                console.log(this.subpackages);
            })
            .catch(e => {
              //...
            })
        }
    }
});

In the console I can see received object dumped like

0:{id: 14, name: "Adult", price: "45.00"}

However select2 reminds unchanged

Shirker
  • 1,233
  • 2
  • 18
  • 30
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – thanksd Feb 15 '18 at 05:08
  • 1
    `this` is not referencing the Vue instance in the function passed to `then`. Set a reference to `this` before the axios call (`let self = this`) and then reference that instead. Or use an arrow function `then((response) => { ... })`, which keeps `this` the same as the parent scope. Reference the post I linked for more info. – thanksd Feb 15 '18 at 05:11
  • yep it works this way. How will I accept your answer? And another question.. Second select now appears blank, even its populated. Is there a way of changing this? – Shirker Feb 15 '18 at 05:19
  • figured out the second question, by changing `this.select2` after populating `subpackages` – Shirker Feb 15 '18 at 05:30

0 Answers0