Vue.js 无法将 get 请求中的数据放入变量中

Vue.js Can't get the data out of a get request into a variable

我是 运行 服务于 Vue.js 应用程序的服务器。 因此,如果我在浏览器中输入 http://localhost:9999/, 浏览器获取 4 个重要文件: post.js、get.js、vue.js 和 index.HTML 与 vue 代码。

我得到了一个动态有序列表,其中每个列表元素都可以工作 有一个按钮来添加一个元素并删除它自己以及 将一些变量输出到控制台的调试按钮。

现在我需要向我的服务器发出获取请求以获取包含 JSON 数据的数组 这将在第二个有序列表中创建一些元素。

我尝试了以下但没有任何效果:

//get("http://localhost:9999/text/1", inputData)
//get("http://localhost:9999/text/1").then(inputData)
//inputData = get("http://localhost:9999/text/1")

这是get.js的内容:

//which is correctly included in the vue.js index.HTML
//<script SRC="get.js"> </script>
function get(url, params) {
        // Return a new promise.
        return new Promise(function(resolve, reject) {
            // Do the usual XHR stuff
            var req = new XMLHttpRequest();
            req.open('GET', url, true);
        req.setRequestHeader('Content-type', 'application/json');

            req.onload = function() {
                // This is called even on 404 etc
                // so check the status
                if (req.status == 200) {
                    // Resolve the promise with the response text
                    //resolve(req.response);
                    resolve(JSON.parse(req.response));
            }
            else {
                // Otherwise reject with the status text
                // which will hopefully be a meaningful error
                reject(req.statusText);
            }
        };

        // Handle network errors
        req.onerror = function() {
            reject("Network Error");
        };

        // Make the request
        req.send(params);
    });
}

在我调用vue.js方法块之后

mounted() {
    this.$nextTick(function () {
    var inputData=[]
    //get("http://localhost:9999/text/1", inputData)
    //get("http://localhost:9999/text/1").then(inputData)
    inputData = get("http://localhost:9999/text/1")
    app.vueData = inputData
    console.log(inputData)
    console.log(JSON.stringify(inputData))
    console.log(';)')
    })
}

Promise 有内容,但我无法将其传递给变量。

Promise {<pending>}
__proto__: Promise
catch: ƒ catch()
constructor: ƒ Promise()
finally: ƒ finally()
then: ƒ then()
Symbol(Symbol.toStringTag): "Promise"
__proto__: Object
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(4)
0: {text: "This List"}
1: {text: "was pulled"}
2: {text: "from the"}
3: {text: "server"}
length: 4
__proto__: Array(0)

由于评论被删除,我必须发挥创意:

@Apal Shah 感谢您的回答。您的代码看起来比 then() 解决方案好得多。 在阅读您的解决方案之前,我通过添加大量 console.log()s

了解了罪魁祸首
console.log('app.vueData vor app.vueData = inputData: ')
console.log(app.vueData)

app.vueData = inputData

console.log('inputData nach Zuweisung: ')
console.log(inputData)

console.log('JSON.stringify(inputData)')
console.log(JSON.stringify(inputData))

console.log(';)')

控制台输出:

get block:                                                                  (index):153
app.vueData vor app.vueData = inputData:                                    (index):156
 [__ob__: Observer]                                                         (index):157
  length: 0
  __ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
  __proto__: Array
inputData nach Zuweisung:                                                   (index):161
 [__ob__: Observer]                                                         (index):162
  length: 0
  __ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
  __proto__: Array
 JSON.stringify(inputData)                                                  (index):164
 []                                                                         (index):165
 ;)                                                                         (index):167

 Download the Vue Devtools extension for a better development experience:   vue.js:9049
 https://github.com/vuejs/vue-devtools

 You are running Vue in development mode.                   vue.js:9058
 Make sure to turn on production mode when deploying for production.
 See more tips at https://vuejs.org/guide/deployment.html

 (4) [{…}, {…}, {…}, {…}]                                                   (index):154
  0: {text: "This List"}
  1: {text: "was pulled"}
  2: {text: "from the"}
  3: {text: "server"}
  length: 4
  __proto__: Array(0)

感谢大家现在就去测试它。

解决方法是:

mounted() {
    this.$nextTick(async function () {

        console.log('get block: ')
        console.log('app.vueData vor app.vueData = get() ')
        console.log(app.vueData)

        //Get is a deferred / asynchronous process / operation
        app.vueData = await get("http://localhost:9999/text/1")

        console.log('app.vueData nach Zuweisung: ')
        console.log(app.vueData)

        console.log('JSON.stringify(app.vueData)')
        console.log(JSON.stringify(app.vueData))
        })

        console.log(';)')
}

需要注意的是 async 必须在函数未安装或 this.$nextTick 之前进行。

您已经创建了一个在 HTTP 请求完成后解析数据的 Promise,但您的代码并未等待此 Promise 解析。

你可以做两件事:
1.使用.then()
2. 使用async/await(我更喜欢这个,因为它看起来很干净)

如果你想使用async/await,

mounted() {
    this.$nextTick(async function () {
    var inputData=[]
    //get("http://localhost:9999/text/1", inputData)
    //get("http://localhost:9999/text/1").then(inputData)
    inputData = await get("http://localhost:9999/text/1")
    app.vueData = inputData
    console.log(inputData)
    console.log(JSON.stringify(inputData))
    console.log(';)')
    })
}

在这段代码中,您可以看到在 this.$nextTick 函数之前有 async 关键字,在您的 get 方法之前有 await 关键字。

如果你想处理错误,你总是可以使用try/catch块。

try {
  inputData = await get("http://localhost:9999/text/1");
} catch (e) {
  console.log(e);
}

如果您是 .then() 的粉丝,您的 mounted 方法将如下所示,

mounted() {
    this.$nextTick(function () {
    var inputData=[]
    get("http://localhost:9999/text/1").then(inputData => {
      app.vueData = inputData
      console.log(inputData)
      console.log(JSON.stringify(inputData))
    });
    console.log(';)')
    })
}