如何在vuejs方法中包含诺言

时间:2018-10-28 01:58:49

标签: vue.js vuejs2 es6-promise

以下代码具有vuejs方法。一个正在通过promise函数调用另一个。如何使handleStart首先被调用,然后一旦完成,foo将被解析,handleStart将完成。 必须首先单击开始按钮

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <button
            @click="handleStart"
            >
            START
        </button>
        <button
        @click="done = true"
        >DONE</button>
        <h1>Start the app: {{start}}</h1>
        <h1>Is it done? {{done}}</h1>


    </div>
    <script>
        var app = new Vue({
            el: '#app', 
            data () {
                return {
                    start: false,
                    done:false 
                }
            }, 
            methods: {
                foo() {
                    return new Promise( (resolve) => {
                        if (this.done) {
                            console.log("done is recorded")
                            resolve("Yaa")
                        }
                    })
                }, 
                handleStart () {
                    this.start = true
                    // how to make this an obsersable 
                    this.foo()
                        .then( (data ) => console.log("I must be printed with:", data))
                }
            }
        })
    </script>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

问题出在if (this.done)检查中。
如果done为假,则承诺将永远无法解决,并且handleStart永远不会接收数据。

如果您需要在更改data后做出反应,请看一下Vue的watchers

答案 1 :(得分:0)

您需要使用观察者来观察this.done的变化

watch: {
  done(newVal, oldVal) {
    if (newVal) {
      // do something
    }
  }
}, 
methods: {
  async handleStart () {
    // how to make this async
    this.start = true
    const data = await this.foo()
    console.log("I must be printed with:", data))
  }
}