On the data problem of vue in mounted

during the mounted cycle, there is no data using the properties in data.

getList() {
  const param = {
    id: this.listQuert.id
  };
  api.workinfo(param).then(response => {
            const data = response.data;
            this.list=data
            console.log(this.list)
  });
}

get the data from api and store it in the this.list attribute,

mounted() {
    console.log(this.list)
},

if you want to use this.list data in mounted, you will print out a default null value

clipboard.png

how to write if you want to use this.list in mounted, thank you

May.25,2021

call this.getList (), in mounted so that this.list can have a value


mounted() {
    this.getList()
    setTimeout(() => {
        console.log(this.list)
    },2000)
}

you can get it this way. I succeeded with this, because getList is asynchronous, so you also need an asynchronous function to print this.list,. Otherwise, you should be able to see that the console first prints out the this.list, in mounted, and then prints out the this.list, in getList to make both of them asynchronous

.

api.workinfo (param). Then (response = > {

)
        const data = response.data;
        this.list=data   1.this 2  getList()
        console.log(this.list)

});


this is an asynchronous problem


can be printed directly in the then method of getList.
if you have to use it in mounted (), try the following way:

            mounted() {
                this.getList().then(() => {
                    console.log(this.list)
                });
            },
            methods: {
                getList() {
                    return Promise.resolve({}).then(() => {
                        const param = {
                            id: this.listQuert.id
                        };
                        return api.workinfo(param).then(response => {
                            const data = response.data;
                            this.list = data
                        });
                    })
                }
            }

you need to execute getList ()
`
mounted () {

first.
this.getList().then(() => {
    console.log(this.list)
});

},
`

Menu