我想在我的模式上显示 pdf 文件,我创建文档 url 生成器和一些 pdfId,我存储在 VUEX 中,在我的 vue 组件上我映射操作,并使用 setTimeout 安装函数,但我被告知那是错误的方式,相反我必须使用 Promise。 这是我的代码
文档 url vuex,
const documentUrlBuilder = new DocumentUrlBuilder()
const document = {
namespaced= true,
state: () => ({
pdf: {
repository: 'medscareInc',
pdfId: null,
url: null,
}
}),
mutations: {
updateDocumentUrl(state, url) {
state.pdf.url = url
}
},
actions: {
async fetchPdfFile({commit, state}), pdfId) {
const response = await documentUrlBuilder.getDocumentById(
state.pdf.repository,
pdfId
);
commit('updateDocumentUrl', response.url);
}
}
getDocumentById
是文档 url 构建器函数
这是我的 vue 组件
<script>
import { mapActions } from 'vuex'
export default {
computed: {
pdfUrl() {
return this.$store.state.pdfs.pdf.url
},
},
mounted() {
setTimeout(() => {
const pdfId = this.$store.state.document.pdf.pdfId // fetching from vuex
this.fetchPdfFile(pdfId)
}, 2500)
},
methods: {
...mapActions('pdfs', {
fetchPdfFile: 'fetchPdfFile',
})
}
}
</script>
我被告知我不能使用 setTimeout,而必须使用 Promise,我该怎么做?
你必须等到你的承诺得到解决。您可以使用
await
或使用 then
。如果你使用 await,你挂载的钩子也必须是异步的。你可以了解更多在这里
如果你想了解更多promises
<script>
import { mapActions } from 'vuex'
export default {
computed: {
pdfUrl() {
return this.$store.state.pdfs.pdf.url
},
},
async mounted() {
await this.fetchPdfFile(pdfId)
const pdfId = this.$store.state.document.pdf.pdfId
},
methods: {
...mapActions('pdfs', {
fetchPdfFile: 'fetchPdfFile',
})
}
}
</script>