N
N
nezdhanov2019-06-10 19:38:31
Vue.js
nezdhanov, 2019-06-10 19:38:31

Vue.JS + axios mounted method doesn't allow changing data in data, why?

There is a component:

<template>
    <table class="table table-bordered table-striped">
        <thead>
        <tr>
            <th>#</th>
            <th>Truck</th>
            <th>action</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="truck in myinfo" class="trucks">
            <td>{{ truck.id }}</td>
            <td>{{ truck.name }}</td>
            <td>
                <router-link :to="{name: 'showTruck', params: {id: truck.id}}" class="btn btn-xs btn-default">
                    show
                </router-link>
            </td>
        </tr>
        </tbody>
    </table>
</template>

And there is the logic of this script:
import axios from 'axios'

    export default {
        data: function () {
            return {
                myinfo: [],
            }
        },
        mounted() {
            var app = this;
             axios.get('/api/get-trucks')
                 .then(function (resp) {
                     app.myinfo = resp.data;
                 })
                 .catch(function (resp) {
                     console.log(resp);
                     alert("Не удалось загрузить компании");
                 })
                 .finally(() => (console.debug(app.myinfo)));
        },
    }

Actually the situation is as follows, the data comes from the server, but the related data is not updated.
I did it according to the precepts of Google and manuals, maybe I missed something, of course, but it seems that I double-checked everything more than once ...
Where did I go wrong here? Why is the data not being updated?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin B., 2019-06-10
@Kostik_1993

It all depends on how data is returned from the server. It is possible to change app.myinfo = resp.data; on app.myinfo = resp.data.data; and everything will work

2
2perca, 2019-06-15
@2perca

instead of a hook mounted(), use created(),
also get rid of , use just this, for example, and rewrite the then and catch blocks to arrow functions. var app = this;this.myinfo = resp.data;

V
Vladislav, 2019-12-18
@vos_50

nezdhanov read how it works thisin asynchronous functions. Inside then, it will work for you this, the only thing you had to write this.myinfoinstead app.myinfo.
of A in order to make it generally beautiful, use arrow functions and then you won’t need a crutch like var app = this;
Here is an example of an arrow function if that

.then((response) => {
                    console.log(this.users);
                    this.users = response.data;
                })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question