0

I have the following simple VueJS app:

window.Vue = require('vue');

new Vue({

    el : '#break-container',

    data : {

        pool_break : {
            'name' : '',
            'description' : '',
            'three_point_break' : false
        }

    },

    methods : {

        fetchBreak : function(){

            axios.get('/break-axios').then(function(response){

                this.pool_break = response.data.break;
                console.log(this.pool_break);

            }.bind(this));

        },
    },

    mounted : function(){

        this.fetchBreak();

    },

});

The response from axios comes in correctly, and console.log prints out:

description: "description here"
id: 4
name: "9 ball"
three_point_break: null
user_id: 1

But in my HTML, pool_break.name fails to show:

<div class="container" id="break-container">
    @{{ pool_break.name }}
</div>

This shows up as blank when the page loads. How do I fix this?

I have tried setting the parameters more directly, like:

this.pool_break.name = response.data.break.name;

But the result is the same.

sveti petar
  • 3,637
  • 13
  • 67
  • 144
  • 3
    try `.then(response => {` instead of `.then(function(response){` – Bravo Nov 18 '19 at 13:03
  • @Bravo Can you explain the different syntax? When I do that the `bind` part throws an error. – sveti petar Nov 18 '19 at 13:05
  • @jovan https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable – George Nov 18 '19 at 13:07
  • 1
    @jovan Basically when you use "this" inside "function", it references the own function, so you need to use an arrow function and "this" will reference the Vue Instance and change the data correctly – Marcelo The Mage Coder Nov 18 '19 at 13:10
  • @Bravo This doesn't solve my problem though. The string still isn't displaying in HTML. Also, the previous version I had worked on a different project, I copied the structure from there. Could there be a different issue? – sveti petar Nov 18 '19 at 13:31
  • just a few suggestions - usually you want `data` to be a function that returns it's data as json. In addition I'd recommend to install the vue devtools for chrome and simply inspect the bindings. And maybe also add your template code. – Frnak Nov 18 '19 at 13:34
  • @FrankProvost Thanks for the tip. In vue devtools I just see the Root component, so I'm not sure how it would help me troubleshoot my issue here. On the right, it says "this instance has no reactive state". – sveti petar Nov 18 '19 at 14:20
  • Argh! The issue was that Vue was included twice in webpack. Once explicitly and once implicitly through app.js (this is a Laravel application). When I got rid of the extra vue initialization everything fell into place. – sveti petar Nov 18 '19 at 14:30
  • oh sorry, didn't see the `.bind` - never mind, the arrow function I suggested does basically the same thing you did with .bind - so, that's odd – Bravo Nov 18 '19 at 23:15

0 Answers0