写法一
<template>
<div
class="demo-img"
v-for="item in demoOption"
:key="item.code"
:style="`background-image: url(${getImageUrl(`../assets/imge/${item.img}.jpeg`)})`"
></div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue';
const demoOption = reactive([
{ label: '图一', code: 'one', img: 'one' },
{ label: '图二', code: 'too', img: 'too' }
])
const getImageUrl = (name:string) => {
return new URL(`${name}`, import.meta.url).href
}
</script>
<style lang="scss" scoped>
.demo-img{
width: 400px;
height: 200px;
background-position: right bottom;
background-repeat: no-repeat;
background-size: 63%;
}
</style>
效果
写法二
<template>
<div
class="demo-img"
v-for="item in demoOption"
:key="item.code"
:style="`background-image: url(${getImageUrl(`${item.img}.jpeg`)})`"
></div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue';
const demoOption = reactive([
{ label: '图一', code: 'one', img: 'one' },
{ label: '图二', code: 'too', img: 'too' }
])
const getImageUrl = (name:string) => {
return new URL(`/src/assets/imge/${name}`, import.meta.url).href
}
</script>
<style lang="scss" scoped>
.demo-img{
width: 400px;
height: 200px;
background-position: right bottom;
background-repeat: no-repeat;
background-size: 63%;
}
</style>
写法三
<template>
<div
class="demo-img"
v-for="item in demoOption"
:key="item.code"
:style="`background-image: url(${item.img})`"
></div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue';
import one from '@/assets/imge/one.jpeg'
import too from '@/assets/imge/too.jpeg'
const demoOption = reactive([
{ label: '图一', code: 'one', img: one },
{ label: '图二', code: 'too', img: too }
])
</script>
<style lang="scss" scoped>
.demo-img{
width: 400px;
height: 200px;
background-position: right bottom;
background-repeat: no-repeat;
background-size: 63%;
}
</style>
写法四
<template>
<div
class="demo-img"
v-for="item in demoOption"
:key="item.code"
:style="`background-image: url(${item.img})`"
></div>
</template>
<script lang="ts" setup>
import { reactive,ref } from 'vue';
const one = ref('/src/assets/imge/one.jpeg')
const too = ref('/src/assets/imge/too.jpeg')
const demoOption = reactive([
{ label: '图一', code: 'one', img: one },
{ label: '图二', code: 'too', img: too }
])
</script>
<style lang="scss" scoped>
.demo-img{
width: 400px;
height: 200px;
background-position: right bottom;
background-repeat: no-repeat;
background-size: 63%;
}
</style>
vue-cli写法参照
精简代码 减少冗余 使用v-for通过require动态设置图片和背景