您现在的位置是:首页 >学无止境 >vite使用vue3 v-for渲染图片时的写法网站首页学无止境

vite使用vue3 v-for渲染图片时的写法

沉迷... 2024-08-11 12:01:02
简介vite使用vue3 v-for渲染图片时的写法

写法一

<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动态设置图片和背景

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。