将数据从chrome.storage加载到vue.js数据中

Rud*_*rer 2 google-chrome google-chrome-app vue.js

我正在构建一个chrome应用程序,并将Vue.js用于选项页面。所以我想从Chrome存储中加载设置并将其放入Vue数据中。

我的问题是,我无法从chrome存储回调内部访问vue组件。每次我在回调中调用它时,所有vue元素都是未定义的。有没有办法让chrome storage cb函数返回一个值,或者给它一个额外的回调。

这是我的代码

name: 'app',
    data: function () {
        return {
            data []
        }
    },
    methods: {
        init: function() {
            chrome.storage.sync.get('series', function (storageData) {
                this.data = storageData   //this is not possible, because this.data is undefined
                })
            });
        }
    },
    created: function () {
        this.init();
    }
}
Run Code Online (Sandbox Code Playgroud)

san*_*oco 5

如果使用ES6并进行转码(首选方法)。注意:箭头函数不会创建新的上下文。

init: function() {
    chrome.storage.sync.get('series', storageData => {
        this.data = storageData
    });
}
Run Code Online (Sandbox Code Playgroud)

ES5解决方法:

init: function() {
    var self = this;
    chrome.storage.sync.get('series', function (storageData) {
        self.data = storageData
    });
}
Run Code Online (Sandbox Code Playgroud)