javascript - vue initialization data assignment error
漂亮男人
漂亮男人 2017-06-26 10:55:47
0
6
775

vue code

<script>
import axios from 'axios';
export default {
    data() {
        return {
            titleList: [],
        }
    },
    created() {
        this.axios.get('XX').then(function(response) {
            console.log(response.data);
            this.titleList=response.data;
        }).catch(function (error) {
            console.log(error);
        });
    }
}
</script>

Error reporting

TypeError: Cannot set property 'titleList' of undefined
Type error, cannot set undefined property,

data

response.data is an object array
I have initialized titleList, but I don’t know why it says it is undefined, please give me an answer

漂亮男人
漂亮男人

reply all(6)
伊谢尔伦

This pointer has changed. You can print out this to see who it points to


Solution

1. Use arrow function
2. Save this (let _this = this)

巴扎黑
.then(res => {
    this.titleList = res;
})
过去多啦不再A梦
this.axios.get('XX')
    .then(function (response) {
      response=response.body;
      this.titleList=response.data;
    })
    .catch(function (error) {
      console.log(error);
})

Try this. If it doesn't work, post the error and take a look!

扔个三星炸死你

This pointer is lost, you can use arrow function, or you can use a variable to save this let _this = this

習慣沉默

When I use axios to request data, I remember to introduce the axios class library globally in the program entry file main.js. After importing it, try using Vue.prototype.$http=axios. Then it can be used globally. As for the upstairs You can try this pointer issue pointed out in the answer given. I am used to the syntax of es6, so arrow functions are generally used in projects

阿神
axios.get('***').then((res) => {
    this.titleList=res.data;
});

Try this way

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template