简体   繁体   English

从 data() Vue.js 中定义的对象调用函数

[英]Call a function from an object defined in data() Vue.js

I have an object (requestParams) in data :我在数据中有一个对象(requestParams):

data () {
  return {
    requestParams:{
      controller : '',
      data : {
        username : "arman",
        password : "1234"
      },
      callBack: function() {
        this.testFunct()
      }
    }
  }
},

And in methods:{} I have :在方法中:{} 我有:

methods: {
  clickedButton()
  {
    this.$store.dispatch('postRequest', {self:this})
  },
  testFunct: function()
  {
    alert(123)
  }
},

The "clickedButton" function, calls a method from actions.js and then the actions.js calls the callBack function from requestParams like this : “clickedButton”函数从actions.js 调用一个方法,然后actions.js 从requestParams 调用callBack 函数,如下所示:

self.requestParams.callBack();

The requestParams.callBack() trigger successfully but this.testFunct() returns this error : requestParams.callBack() 触发成功,但 this.testFunct() 返回此错误:

Uncaught (in promise) TypeError: this.testFunct is not a function

How can i call "testFunct" in an object in data() ?如何在 data() 的对象中调用“testFunct”? Thanks.谢谢。

Correct answer to your question depends a little bit on version of ES you are using.您问题的正确答案取决于您使用的 ES 版本。 If you are using ES6 (or higher), then you can use Arrow function like this:如果您使用的是 ES6(或更高版本),那么您可以像这样使用Arrow 函数

data () {
  return {
    requestParams:{
      controller : '',
      data : {
        username : "arman",
        password : "1234"
      },
      callBack: () => { // arrow function does not redeclare `this`
        this.testFunct()
      }
    }
  }
},

If you are using ES5, then you should assign this to any local variable inside your data method:如果使用的是ES5,那么你应该分配this给你内部的任何局部变量data的方法:

data () {
  var that = this;
  return {
    requestParams:{
      controller : '',
      data : {
        username : "arman",
        password : "1234"
      },
      callBack: function() {
        that.testFunct() // using `that`, not `this`
      }
    }
  }
},

And of course you can use second variant with ES6.当然,您可以在 ES6 中使用第二个变体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM