繁体   English   中英

Vue.js - 从回调函数访问数据变量

[英]Vue.js - Access data variable from callback function

我正在使用 Deezer Javascript SDK 播放音轨。

在他们的文档中定义了一堆事件,例如player_loadedplayer_pausedtrack_end等。

它们还展示了如何订阅事件:

// Callback function is called when the current player has resumed or started playing
DZ.Event.subscribe('player_play', function(evt_name){
    console.log("Player is playing");
});
 
// Callback function is called when the currently playing track has changed
DZ.Event.subscribe('current_track', function(track, evt_name){
    console.log("Currently playing track", track);
});
 
// Callback function is called when the volume level of the current player has changed
DZ.Event.subscribe('volume_changed', function(args, evt_name){
    console.log("The current volume level is " + args);
});

到目前为止,这工作正常。

我想知道是否可以从内部函数中访问变量

DZ.Event.subscribe("track_end", function (evt_name) {
            console.log("event fired 1");
            //trying to access this bool var that is defined in data
            this.isDeezerPlaying = false;
});

这是行不通的。 我必须this作为参数传递给回调函数,以便访问我的局部变量isDeezerPlaying 但不是我调用这个函数并传递参数,而是 SDK 在 hud 下的某个地方执行此操作。

那么还有办法吗?

尝试使用以下代码:

const vm = this;
DZ.Event.subscribe("track_end", function (evt_name) {
   console.log("event fired 1");
   //trying to access this bool var that is defined in data
   vm.isDeezerPlaying = false;
});

是的,您可以使用箭头函数:

DZ.Event.subscribe("track_end", (evt_name) => {
            console.log("event fired 1");
            this.isDeezerPlaying = false;
});

“this”关键字如何工作?

https://stackoverflow.com/a/24900924/5671919

是的你可以。 你要么使用箭头函数

DZ.Event.subscribe("track_end", (evt_name) => {
            console.log("event fired 1");
            //trying to access this bool var that is defined in data
            this.isDeezerPlaying = false;
});

或者你绑定它:

DZ.Event.subscribe("track_end", function (evt_name) {
            console.log("event fired 1");
            //trying to access this bool var that is defined in data
            this.isDeezerPlaying = false;
}.bind(this));

暂无
暂无

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

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