search

Home  >  Q&A  >  body text

javascript - vue initialization data assignment error

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

漂亮男人漂亮男人2750 days ago809

reply all(6)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-06-26 10:57:47

    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)

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-26 10:57:47

    .then(res => {
        this.titleList = res;
    })

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-26 10:57:47

    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!

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-26 10:57:47

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

    reply
    0
  • 習慣沉默

    習慣沉默2017-06-26 10:57:47

    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

    reply
    0
  • 阿神

    阿神2017-06-26 10:57:47

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

    Try this way

    reply
    0
  • Cancelreply