( JavaScript已经回答了这个问题,请参见下面的内容,但是这个问题是针对TypeScript的,它的行为不同)
我试图使用类型记录在Vue3.0中使用异步功能。
没有异步,这段代码工作得很好:
// file: components/HelloWorld.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
<script lang="ts">
import {defineComponent} from 'vue'
export default defineComponent({
name: 'HelloWorld',
props: {
msg: String,
},
async setup() { // <-- this works without 'async'
const test = 'test'
// await doSomethingAsynchronous()
return {
test,
}
},
})
</script>使用async setup(),组件"HelloWorld“从页面中消失,火狐控制台告诉我
"Uncaught (in promise) TypeError: node is null (runtime-dom.esm-bundler.js)"当我将async setup()更改为setup()时,代码可以工作,但这样我就无法在安装函数中使用异步/等待。
因此,我的问题是:如何在使用类型记录的setup()函数中使用异步/等待?
编辑:
这个问题的答案是:为什么在Vue3中使用异步安装程序()时出现空显示async setup()确实与JavaScript一起工作,所以我希望它也能在TypeScript中工作。
发布于 2020-09-29 10:02:47
尝试使用onMounted钩子操作异步调用:
setup() {
const users = ref([]);
onMounted(async () => {
const res = await axios.get("https://jsonplaceholder.typicode.com/users");
users.value = res.data;
console.log(res);
});
return {
users,
};
},但是,最佳方法是在子组件中使用async setup,并在父组件中用Suspense组件包装该组件:
UserList.vue
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
async setup() {
//get users from jsonplacerholder using await fetch api
const users = await fetch("https://jsonplaceholder.typicode.com/users").then(res => res.json());
return {
users
}
}
})
</script>
<template>
<div>
<!-- list users -->
<ul>
<li v-for="user in users">{{ user.name }}</li>
</ul>
</div>
</template>父组件
<script lang="ts">
import UserList from "../components/tmp/UserList.vue";
...
</script>
<div>
<!-- Suspense component to show users -->
<Suspense>
<template #fallback>
<div>loading</div>
</template>
<UserList />
</Suspense>
</div>发布于 2021-05-13 19:30:15
另一种做法是:
const users = ref([]);
(async () => {
const res = await axios.get("https://jsonplaceholder.typicode.com/users");
users.value = res.data;
console.log(res);
})()
return {
users,
}您不必等待它挂载,这类似于在options中使用created()。
注意:不要忘记在函数语句之前总是有分号";“否则,JavaScript会认为前面的语句应该返回一个函数,例如,下面的代码会导致错误"ref([])不是函数”:
const users = ref([]) // No semicolon here
(async () => {防止此错误的另一种方法是在函数定义的同一行中始终使用分号,下面的代码也能工作:
;(async () => {发布于 2021-06-29 09:11:31
另一种选择是使用承诺链,这样做的好处是代码甚至在beforeCreate生命周期挂钩之前运行:
import { defineComponent, ref } from 'vue'
import { getData } from './api.js'
export default defineComponent({
setup() {
const users = ref([])
getData().then(({ data }) => (users.value = data))
return {
users,
}
},
})https://stackoverflow.com/questions/64117116
复制相似问题