![](/img/trans.png)
[英]Vue.js - Trying to pass object from data() to a mounted() function
[英]Call a function from an object defined in data() Vue.js
我在數據中有一個對象(requestParams):
data () {
return {
requestParams:{
controller : '',
data : {
username : "arman",
password : "1234"
},
callBack: function() {
this.testFunct()
}
}
}
},
在方法中:{} 我有:
methods: {
clickedButton()
{
this.$store.dispatch('postRequest', {self:this})
},
testFunct: function()
{
alert(123)
}
},
“clickedButton”函數從actions.js 調用一個方法,然后actions.js 從requestParams 調用callBack 函數,如下所示:
self.requestParams.callBack();
requestParams.callBack() 觸發成功,但 this.testFunct() 返回此錯誤:
Uncaught (in promise) TypeError: this.testFunct is not a function
如何在 data() 的對象中調用“testFunct”? 謝謝。
您問題的正確答案取決於您使用的 ES 版本。 如果您使用的是 ES6(或更高版本),那么您可以像這樣使用Arrow 函數:
data () {
return {
requestParams:{
controller : '',
data : {
username : "arman",
password : "1234"
},
callBack: () => { // arrow function does not redeclare `this`
this.testFunct()
}
}
}
},
如果使用的是ES5,那么你應該分配this
給你內部的任何局部變量data
的方法:
data () {
var that = this;
return {
requestParams:{
controller : '',
data : {
username : "arman",
password : "1234"
},
callBack: function() {
that.testFunct() // using `that`, not `this`
}
}
}
},
當然,您可以在 ES6 中使用第二個變體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.