如何解决Vue组件中“未定义”变量的问题

时间:2019-09-20 12:13:35

标签: vue.js

我正在尝试从Vue.js中的数组中操作数据,特别是试图简单地打印出一个变量值,因为现在我什至无法使用它。

我尝试了不同的语法来使其工作,但似乎尚未附加数据。

  el: '#profile',
  delimiters: ['${','}'],
  data: {
    component: null,
    component_info:  null,
    loading: true,
    fields: [
        ],
  },
  beforeMount: function(){
    this.whatever2=document.getElementsByClassName('token-carrier')[0].getAttribute('token') || '';
 },
  mounted: function() {
    this.getComponent();
  },
  computed: function(){
    console.log(this.component['name'].value); //value is undefined
  },
  methods: {
    getComponent: function() {
      let api_url = '/api/component/' + '?' + 'id=' + this.whatever2;
      this.loading = true;

      this.$http.get(api_url)
          .then((response) => {
            this.component = response.data[0];
            this.loading = false;
          })
          .catch((err) => {
            this.loading = false;
            console.log(err);
          })
    },
  }
});```

1 个答案:

答案 0 :(得分:0)

使用了created()方法,并在其中调用this.getComponent();

 created: function() {
    this.getComponent();
  },

更新:  还有另一个问题

 this.component = response.data[0];

此行有错误,因为关键字this不表示您的范围, 试试这个:

      var that = this;

      this.$http.get(api_url)
          .then((response) => {
            that.component = response.data[0];
            that.loading = false;
          })
          .catch((err) => {
            that.loading = false;
            console.log(err);
          })