Vue错误:在严格模式代码中,只能在顶层或块内声明函数

时间:2019-07-31 08:55:21

标签: javascript html vue.js xmlhttprequest

我正在运行带有文本框和提交按钮的 Vue 脚本,我正在调用api以将我在文本框中编写的内容发布到api并从API返回信息,尽管我已经按照应有的方式编写了Javascript函数,但标题中还是出现了此错误?

使用脚本我首先设置一个新的XMLHttpRequest,为GET和POST方法启动标头和api键。然后,我创建了2个函数以从文本框中获取数据并将其发送到API,然后使用另一个函数创建另一个按钮以将数据发送回。

我之所以采用这种方法,是因为我一直遇到CORS问题,并且API需要我声明一个访问控制源标头,我对这段代码做错了什么吗?任何帮助将不胜感激

<script>
export default {
    name: 'ProperForm'
}
    methods: {
        StartClient: function () {
            this.get = function(Url, Callback){
            var aHttpRequest = new XMLHttpRequest();
            aHttpRequest.onreadystatechange = function() {
                if (aHttpRequest.readyState == 4 && aHttpRequest.status == 200)
                Callback(aHttpRequest.responseText);
            }

            aHttpRequest.open("GET", Url, true);
            aHttpRequest.setRequestHeader("X-Api-Key", "eVnbxBPfn01kuoJIdfgi46TiYNv8AIip1r3WbjsX");
            aHttpRequest.send(null);
        }
        this.post = function(Url, message, Callback) {
            var aHttpRequest = new XMLHttpRequest();
            aHttpRequest.onreadystatechange = function() {
                if (aHttpRequest.readyState == 4 && aHttpRequest.status == 200)
                Callback(aHttpRequest.responseText);
            }

            aHttpRequest.open("POST", Url, true);
            aHttpRequest.setRequestHeader("x-api-key", "eVnbxBPfn01kuoJIdfgi46TiYNv8AIip1r3WbjsX");
            aHttpRequest.send(message);
            }
        }
    var client = new StartClient();

    submitData: function () {
        document.getElementById('inputBox').disabled = true;
        var targetInputButton = document.getElementById("inputBox").value;
        var message = '{"targetInputButton":"' + targetInputButton + '"}';
        client.post('https://le75bkfcmg.execute-api.eu-west-2.amazonaws.com/dev/start-trace', message, function(response) {
        document.getElementById('jobId').innerHTML = response;
    });
    }

    sendBackData: function () {
        var jobId = document.getElementById("jobId").innerHTML;
        var message = '{"jobId":"' + jobId + '"}';
        client.post('https://le75bkfcmg.execute-api.eu-west-2.amazonaws.com/dev/check-trace', message, function(response) {
        document.getElementById('report').innerHTML = response;
    });
    }
}

</script>

我编写var client的新方法:

StartClient: function () {
    var client 
},

1 个答案:

答案 0 :(得分:0)

您需要将您的methods对象放入export并将这些方法拆分为逗号

<script>
export default {
    name: 'name',
    methods:{
        foo(){
        },
        bar(){
        }
    }
}

UPD:var client = new StartClient(); 在方法之外定义