如何在 Vue.js 中繫結背景圖片?
v-bind:style 的值只是一個普通的 JavaScript 物件,它遵循一些繫結內容的規則。背景圖片的值應該是一個字串。因此,我們可以使用 style 標籤在 Vue.js 中應用或資料繫結背景圖片,然後在其中定義 backgroundImage URL。它將自動從字串中檢索 url,然後在瀏覽器網頁上顯示相同的資料內容。
要訪問背景圖片,請建立一個 div 元素,並在其中使用 url 定義背景圖片。該 url 將從 JS 檔案中檢索。
示例
將下面的程式碼片段複製貼上到你的 Vue 專案中,然後執行 Vue 專案。你將在瀏覽器視窗中看到下面的輸出。
檔名 - app.js
目錄結構 -- $project/public -- app.js
// Defining image link new Vue({ el: "#app", data: { image:"https://store-images.s-microsoft.com/image/apps.2366.9007199266518672.0607cbef-4e96-49c1-b02c-2432d9fc4826.e2043c6d-d6c4-49ed-8199-cc06665e9e9f" } })
檔名 - index.html
目錄結構 -- $project/public -- index.html
<!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body> <div id="app"> <div class="circular" :style="{ backgroundImage: 'url(' + image + ')' }"> </div> </div> <script src='app.js'></script> </body> </html>
檔名 – styles.css
目錄結構 -- $project/public -- styles.css
.circular{ width: 200px; height: 200px; background-size: cover; border-radius: 50px; -webkit-border-radius: 50px; -moz-border-radius: 50px; }
執行以下命令以獲得以下輸出:
C://my-project/ > npm run serve
完整程式碼
現在讓我們使用以上三個檔案(app.js、index.html 和 styles.css)建立一個完整的程式。我們可以將此程式碼作為 HTML 程式執行。
<!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <style> .circular { width: 200px; height: 200px; background-size: cover; border-radius: 50px; -webkit-border-radius: 50px; -moz-border-radius: 50px; } </style> </head> <body> <div id="app"> <div class="circular" :style="{ backgroundImage: 'url(' + image + ')' }"> </div> </div> <script> // Defining image link new Vue({ el: "#app", data: {image: "https://store-images.s-microsoft.com/image/apps.2366.9007199266518672.0607cbef-4e96-49c1-b02c-2432d9fc4826.e2043c6d-d6c4-49ed-8199-cc06665e9e9f" } }) </script> </body> </html>
在這篇文章中,我們演示瞭如何在 Vue.js 中繫結背景圖片。為了執行此任務,我們建立了 app.js、index.html 和 styles.css 檔案,並使用 <script> 標籤在 index.html 檔案中包含了 app.js 和 styles.css 檔案。最後,我們透過將 app.js、styles.css 和 index.html 組合成單個 HTML 檔案來建立完整的程式碼。
廣告