使用 VueJS 檢查瀏覽器中影像是否已載入?


無論何時我們在任何系統的前端插入影像,顯示正確的資料和影像以增強使用者體驗都非常重要。在任何專案中,影像基本上是從遠端路徑 URL 或應用程式載入的。在以下情況下,影像可能無法正確載入:

  • 配置錯誤的影像 URL

  • 糟糕的網際網路/網路連線

檢查影像是否已載入非常重要,因為如果由於網路連線不良導致影像未載入,我們可以嘗試再次載入影像。在這裡,我們將使用 <img> 標籤來檢查影像是否已成功載入。

  • @load - 當影像載入並執行時觸發此事件。在影像成功載入之前,它不會執行。

語法

以下是我們可以使用 Vue.js 檢查影像是否已載入的語法:

data () {
   return {
      isLoaded: false
   }
},
methods: {
   onImgLoad () {
      this.isLoaded = true
   }
}

在這裡,如果影像成功載入,則 isLoaded 標誌設定為 'true',否則設定為 'false'

示例:檢查影像是否已載入

將您的影像檔案放入您的 VueJS assets 資料夾中,以便稍後可以檢索它。以下是您需要放置檔案的位置,以便 VueJS 可以讀取它。

Directory Structure – $Project_name
			   |--- public
	                    |--- ** Place your file here **

將下面的程式碼片段複製貼上到您的 Vue 專案中並執行 Vue 專案。您將在瀏覽器視窗中看到以下輸出。

  • 檔名 - app.js

  • 目錄結構 -- $project/public -- app.js

// Calling the function- onImgLoad() when image is loaded
const parent = new Vue({
   el: "#parent",
   data () {
      return {
         isLoaded: false
      }
   },
   methods: {
      onImgLoad () {
         this.isLoaded = true
      }
   }
})
  • 檔名 - index.html

  • 目錄結構 -- $project/public -- index.html

<!DOCTYPE html>
<html>
<head>
   <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
   <title> Checking if an image is loaded or not </title>
   <body>
      <div id='parent'>
         <img src="tutorialspoint.png" alt="Image" @load="onImgLoad">
         <h2>Image Loaded : {{isLoaded}} </h2>
      </div>
      <script src='app.js'></script>
   </body>
</html>

執行以下命令以獲得以下輸出:

C://my-project/ > npm run serve

包含 HTML 的完整程式碼

以下是包含 HTML 的完整程式碼。我們將 app.js 與 index.html 新增在一起形成單個檔案。您現在可以將以下程式碼作為 HTML 檔案執行。

<!DOCTYPE html>
<html>
<head>
   <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
   <title> Checking if an image is loaded or not </title>
   <body>
      <div id='parent'>
         <img src="https://tutorialspoint.tw/static/images/logo-color.png" alt="Image" @load="onImgLoad">
         <h2>Image Loaded : {{isLoaded}} </h2>
      </div>
      <script>
      
         // Calling the function- onImgLoad() when image is loaded
         const parent = new Vue({
            el: "#parent",
            data () {
               return {
                  isLoaded: false
               }
            },
            methods: {
               onImgLoad () {
                  this.isLoaded = true
               }
            }
         })
      </script>
   </body>
</html>

當影像成功載入時,訊息顯示為“影像載入:true”,否則顯示“影像載入:false”。

您可以更改影像 src 路徑並檢查不同的影像。還可以檢查不存在的影像。

更新於:2023年4月12日

2K+ 次檢視

啟動您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.