它的工作原理包括img
元素,並顯示通過CSS隱藏它們。
<template>
<div>
<img class="image--sm" :src="src.sm" />
<img class="image--md" :src="src.md" />
<img class="image--lg" :src="src.lg" />
</div>
</template>
<script>
export default {
props: {
src: Object
}
}
</script>
<style>
.image--md,
.image--lg {
display: none;
}
@media (min-width: 400px) {
.image--sm {
display: none;
}
.image--md {
display: block;
}
}
@media (min-width: 600px) {
.image--md {
display: none;
}
.image--lg {
display: block;
}
}
</style>
實施例:https://jsfiddle.net/h3c5og08/1/
解決方案2:
圖片代碼可能不是你正在努力實現期望的效果。此解決方案在頭部創建一個樣式標籤,並注入CSS內容以更改背景圖像。
Vue模板中不能有樣式標籤。它會拋出一個錯誤,如:
模板只應負責將狀態映射到UI。避免在模板中放置帶副作用的標籤,例如,因爲它們不會被解析。
由於錯誤描述vue設計的地圖狀態UI。禁止在模板中使用style
標籤,因爲您可能導致泄漏到外部世界。
儘管您無法在模板中聲明樣式,但我們可以在組件的裝入掛鉤中使用一些JS來添加目標樣式和動態樣式。
首先,我們需要將動態樣式約束到這個元素。我們可以使用創建的組件this._uid
的內部ID,附加到範圍的CSS。 (注意,這是內部API所以可以隨時更改)
<template>
<div class="image" :data-style-scope="_uid">
</div>
</template>
接下來的部分是產生在計算屬性的樣式,到後來注入的樣式塊。您可以擴展此計算屬性,以條件分配屬性等。注意:僅將屬性保留爲動態值。
css() {
const selector = `.image[data-style-scope="${this._uid}"]`
const img = val => `${selector} { background-image: url("${val}"); }`
const sm = img(this.sm)
const md = img(this.md)
const lg = img(this.lg)
return `
${sm}
@media (min-width: 200px) { ${md} }
@media (min-width: 300px) { ${lg} }
`
}
從css
計算財產這生成的字符串就是創建在掛載的風格標籤,當我們將現在使用。在裝載時,我們創建一個樣式節點並追加到頭部。將節點分配給vm以供參考。
使用vm中的引用我們可以觀察計算更新樣式節點的更改。
請記住在清除組件之前進行清理,刪除樣式節點。
{
data() {
return {
// Reference data properties
style: null,
styleRef: null
}
},
mounted() {
// Create style node
let style = document.createElement('style')
style.type = "text/css"
style.appendChild(document.createTextNode(''))
// Assign references on vm
this.styleRef = style
this.style = style.childNodes[0]
// Assign css the the style node
this.style.textContent = this.css
// Append to the head
document.head.appendChild(style)
},
beforeDestroy() {
// Remove the style node from the head
this.style.parentElement.removeChild(this.style)
},
computed: {
css() {
// ...
}
},
watch: {
css (value) {
// On css value change update style content
this.style.textContent = this.css
}
}
}
工作實例:https://jsfiddle.net/bLkc51Lz/4/
喜歡的東西https://css-tricks.com/responsive-images-youre-just-changing-resolutions-use-srcset/? –
您還沒有顯示任何圖像大小以及如何確定您是否需要'src-md'或'src-lg'?你試過什麼了? –
@RoyJ這看起來不錯,但我不認爲它適用於背景圖片(糾正我,如果我錯了)。 – Moshe