【问题标题】:Cannot set property of undefined within a function无法在函数中设置未定义的属性
【发布时间】:2019-02-15 08:51:42
【问题描述】:

我正在使用 vue 在扩展程序的登录页面上设置错误消息,并且在 importCreds() 函数中出现错误。

data(){
    return {
    url:'',
    apikey:'',
    error:'',
    }
},
methods:{
    accountSummaryButton(){
        if (localStorage.getItem("accounts") == null)
            this.error = 'There are no available accounts.';
        }
        else
            // STUFF
    },
    saveLogin(event){
        let app = this;
        if (!app.getAccountData(app.url,app.apikey,this.method))
            this.error = 'An error has occurred, please check Url and API Key.';
        else {
            //STUFF
        }
    },
    importCreds(){
        let app = this;
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
            chrome.tabs.sendMessage(
                tabs[0].id,
                {action: "import_creds"},
                function(response) {
                    if (response){
                        app.url = response.affiliateurl
                        app.apikey = response.apikey
                    } else
                        this.error = 'Go to your affiliate site.';
                }
            );
        });
    },
},

我是否缺少在该函数中访问 error 的简单方法?

【问题讨论】:

    标签: javascript vue.js undefined typeerror


    【解决方案1】:

    importCreds 仍然引用原始的 this,但是 chrome.tabs.query({}, function(tabs) {}) 不是。您可以通过将this 分配给变量e.g. (let app = this) 来保留该引用,然后使用app.error

    data () {
        return {
          url: '',
          apikey: '',
          error: '',
        }
    },
    methods: {
        accountSummaryButton () {
            if (localStorage.getItem("accounts") == null) {
                this.error = 'There are no available accounts.';
            } else {
                // STUFF
            }
        },
        saveLogin (event) {
            let app = this;
    
            if (!app.getAccountData(app.url,app.apikey,this.method)) {
                this.error = 'An error has occured, please check Url and API Key.';
            } else {
                // STUFF
            }
        },
        importCreds () {
            let app = this;
    
            chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
                chrome.tabs.sendMessage(
                    tabs[0].id,
                    { action: "import_creds" },
                    function(response) {
                        if (response) {
                            app.url = response.affiliateurl
                            app.apikey = response.apikey
                        } else {
                            app.error = 'Go to your affiliate site.';
                        }
                    }
                );
            });
        },
    },
    

    【讨论】:

    • 是的,让我感觉很愚蠢,尤其是看到我在上面的行中使用了app。谢谢!
    猜你喜欢
    • 2021-11-27
    • 2022-10-30
    • 2023-02-10
    • 2015-12-07
    • 2013-05-28
    • 2016-02-23
    • 2011-11-20
    相关资源
    最近更新 更多