vue3 promise使用方法
在Vue3中,可以使用setup函数来使用Promise。下面是一个简单的例子:
import { ref, onMounted } from 'vue'
export default {
setup() {
const result = ref(null)
onMounted(() => {
// 使用Promise
const promise = new Promise((resolve, reject) => {
// 模拟异步操作
setTimeout(() => {
resolve('Promise resolved!')
}, 1000)
})
promise.then((data) => {
// 将结果保存到ref中
result.value = data
})
})
return {
result
}
}
}
在上面的例子中,我们使用ref创建了一个响应式的变量result,并在onMounted钩子函数中使用Promise来模拟一个异步操作。当Promise被解析后,我们将结果保存到result变量中。
注意,setup函数是Vue3中用于替代created和mounted生命周期钩子函数的新特性
原文地址: https://www.cveoy.top/t/topic/hAtA 著作权归作者所有。请勿转载和采集!