如何在vuejs方法中包含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>

您需要使用观察程序来观察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))
}
}

问题出在if (this.done)检查上
done为false时,promise永远不会被解析,handleStart也永远不会接收数据。

如果你需要在data发生变化时做出反应,请查看Vue的观察者

最新更新