未捕获的类型错误:从 Vue 中的数据调用方法时不是一个函数

por*_*der 6 javascript vue.js

当我运行以下命令时,出现错误:“Uncaught TypeError: this.thePerson is not a function”:

var myApp = new Vue({
    el: "#app",
    data: {
        person: [this.thePerson()]
    },
    methods: {
        thePerson: function() {
            return {
                personNickname: "Bob",
                personOwes: 0,
                paymentType: {
                    card: true,
                    cash: false
                }
            };
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

我不明白为什么!

PS我意识到这是看起来很奇怪的代码,但是我使用函数返回数组内容是有原因的......

Eri*_*uan 6

转变data成一个函数。

var myApp = new Vue({
    el: "#app",
    data: function() {
        return {
            person: [this.thePerson()]
        }
    },
    methods: {
        thePerson: function() {
            return {
                personNickname: "Bob",
                personOwes: 0,
                paymentType: {
                    card: true,
                    cash: false
                }
            };
        }
    }
});
Run Code Online (Sandbox Code Playgroud)


小智 2

您是否尝试在 Vue 的创建方法上分配 person 值?

根据你的例子:

    var myApp = new Vue({
  el: "#app",
  data: {
      person: []
  },
  methods: {
      thePerson: function() {
          return {
              personNickname: "Bob",
              personOwes: 0,
              paymentType: {
                  card: true,
                  cash: false
              }
          };
      }
  },
  created(){
    this.person.push(this.thePerson())
  }
});
Run Code Online (Sandbox Code Playgroud)