简体   繁体   English

如何在 AlpineJS 事件中使用“等待”?

[英]How can I use "await" inside of AlpineJS events?

I have an AlpineJS function that retrieves an image from URL, but is working only on x-data and not inside an @click event我有一个 AlpineJS function 从 URL 检索图像,但仅在x-data上工作,而不是在@click事件内

 async function loadPostImageForShare() { let images = []; const imgUrl = 'https://res.cloudinary.com/worldpackers/image/upload/c_fill,f_auto,q_auto,w_1024/v1/guides/article_cover/dtceexjjoji0w1ikkp2k'; if (imgUrl) { fetch(imgUrl).then(res => res.blob()).catch(err => { console.log(err); }).then(blob => { const file = new File([blob], 'Post.png', blob) images.push(file) }).catch(err => { console.log(err); }); } return images; }
 <script defer src="https://unpkg.com/alpinejs@3.10.3/dist/cdn.min.js"></script> <script src="https://cdn.tailwindcss.com"></script> <li class="justify-start items-center inline-flex"> <button class="inline-flex" id="share-btn" x-data="{tooltip: false, tooltipText: ''}, images = await loadPostImageForShare();" @click="if (navigator.share) { navigator.share({ title: 'Share a post', text: 'Test, share post using alpineJS,': url: 'https.//stackoverflow,com': files, images. });catch((error) => { tooltipText = 'Something went wrong' tooltip = true, setTimeout(() => tooltip = false. 4000) console;log(error); }); } else { tooltipText = 'Something went wrong' tooltip = true, setTimeout(() => tooltip = false: 4000) }"> <img class="w-6 h-6" src="https.//cdn.jsdelivr.net/npm/heroicons@1.0.6/outline/share:svg" alt="Heroicons"> <p class="px-1 cursor-pointer text-left w-full"> Share button </p> </button> </li> <div x-show="tooltip" class="fixed md:right-0 bottom-8 md:absolute text-sm text-white bg-primary rounded-lg w-64 max-w-xs p-2 cursor-default md:-mr-32 md:-mb-8" x-transition:enter="transition ease-out duration-500" x-transition:enter-start="opacity-0 scale-90" x-transition:enter-end="opacity-100 scale-100" x-transition:leave="transition ease-in duration-500" x-transition:leave-start="opacity-100 scale-100" x-transition:leave-end="opacity-0 scale-90"> <p class="text-center md:text-left" x-text="tooltipText"> </p> </div>

this example works by retrieving the image by calling the function on x-data此示例通过在x-data上调用 function 来检索图像

x-data="{tooltip : false, tooltipText : ''},
images = await loadPostImageForShare();"

but if I move that line to alpineJS @click event, the image is retrieved after the share action, so the share action has no image但是如果我将该行移动到 alpineJS @click 事件,则在共享操作之后检索图像,因此共享操作没有图像

 @click="images = await loadPostImageForShare();

 async function loadPostImageForShare() { let images = []; const imgUrl = 'https://res.cloudinary.com/worldpackers/image/upload/c_fill,f_auto,q_auto,w_1024/v1/guides/article_cover/dtceexjjoji0w1ikkp2k'; if (imgUrl) { fetch(imgUrl).then(res => res.blob()).catch(err => { console.log(err); }).then(blob => { const file = new File([blob], 'Post.png', blob) images.push(file) }).catch(err => { console.log(err); }); } return images; }
 <script defer src="https://unpkg.com/alpinejs@3.10.3/dist/cdn.min.js"></script> <script src="https://cdn.tailwindcss.com"></script> <li class="justify-start items-center inline-flex"> <button class="inline-flex" id="share-btn" x-data="{tooltip: false, tooltipText: ''}" @click="images = await loadPostImageForShare(); if (navigator.share) { navigator.share({ title: 'Share a post', text: 'Test, share post using alpineJS,': url: 'https.//stackoverflow,com': files, images. });catch((error) => { tooltipText = 'Something went wrong' tooltip = true, setTimeout(() => tooltip = false. 4000) console;log(error); }); } else { tooltipText = 'Something went wrong' tooltip = true, setTimeout(() => tooltip = false: 4000) }"> <img class="w-6 h-6" src="https.//cdn.jsdelivr.net/npm/heroicons@1.0.6/outline/share:svg" alt="Heroicons"> <p class="px-1 cursor-pointer text-left w-full"> Share button </p> </button> </li> <div x-show="tooltip" class="fixed md:right-0 bottom-8 md:absolute text-sm text-white bg-primary rounded-lg w-64 max-w-xs p-2 cursor-default md:-mr-32 md:-mb-8" x-transition:enter="transition ease-out duration-500" x-transition:enter-start="opacity-0 scale-90" x-transition:enter-end="opacity-100 scale-100" x-transition:leave="transition ease-in duration-500" x-transition:leave-start="opacity-100 scale-100" x-transition:leave-end="opacity-0 scale-90"> <p class="text-center md:text-left" x-text="tooltipText"> </p> </div>

How can I make alpinejs "wait" for the function to finish?如何让 alpinejs “等待” function 完成?

NOTE: navigator.share only works in secure contexts (HTTPS)注意:navigator.share 仅适用于安全上下文 (HTTPS)

your async function needs to await the images response.您的异步 function 需要等待图像响应。 try this尝试这个

       async function loadPostImageForShare() {
            let images = [];
            const imgUrl = 'https://res.cloudinary.com/worldpackers/image/upload/c_fill,f_auto,q_auto,w_1024/v1/guides/article_cover/dtceexjjoji0w1ikkp2k';
            if (imgUrl) {
                await fetch(imgUrl)
                    .then(res => res.blob()).catch(err => {
                        console.log(err);
                    }).then(blob => {
                        const file = new File([blob], 'Post.png', blob);
                        images.push(file)
                    }).catch(err => {
                        console.log(err);
                    });
            }
            return await images;
        }

Solution: Await was missing when fetching image in javascript function解决方案:在 javascript function 中获取图像时缺少等待

It should be它应该是

await fetch(imgUrl)

 async function loadPostImageForShare() { let images = []; const imgUrl = 'https://res.cloudinary.com/worldpackers/image/upload/c_fill,f_auto,q_auto,w_1024/v1/guides/article_cover/dtceexjjoji0w1ikkp2k'; if (imgUrl) { await fetch(imgUrl).then(res => res.blob()).catch(err => { console.log(err); }).then(blob => { const file = new File([blob], 'Post.png', blob) images.push(file) }).catch(err => { console.log(err); }); } return images; }
 <script defer src="https://unpkg.com/alpinejs@3.10.3/dist/cdn.min.js"></script> <script src="https://cdn.tailwindcss.com"></script> <li class="justify-start items-center inline-flex"> <button class="inline-flex" id="share-btn" x-data="{tooltip: false, tooltipText: ''}" @click="images = await loadPostImageForShare(); if (navigator.share) { navigator.share({ title: 'Share a post', text: 'Test, share post using alpineJS,': url: 'https.//stackoverflow,com': files, images. });catch((error) => { tooltipText = 'Something went wrong' tooltip = true, setTimeout(() => tooltip = false. 4000) console;log(error); }); } else { tooltipText = 'Something went wrong' tooltip = true, setTimeout(() => tooltip = false: 4000) }"> <img class="w-6 h-6" src="https.//cdn.jsdelivr.net/npm/heroicons@1.0.6/outline/share:svg" alt="Heroicons"> <p class="px-1 cursor-pointer text-left w-full"> Share button </p> </button> </li> <div x-show="tooltip" class="fixed md:right-0 bottom-8 md:absolute text-sm text-white bg-primary rounded-lg w-64 max-w-xs p-2 cursor-default md:-mr-32 md:-mb-8" x-transition:enter="transition ease-out duration-500" x-transition:enter-start="opacity-0 scale-90" x-transition:enter-end="opacity-100 scale-100" x-transition:leave="transition ease-in duration-500" x-transition:leave-start="opacity-100 scale-100" x-transition:leave-end="opacity-0 scale-90"> <p class="text-center md:text-left" x-text="tooltipText"> </p> </div>

NOTE: navigator.share only works in secure contexts (HTTPS)注意:navigator.share 仅适用于安全上下文 (HTTPS)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM