Как на Vue добавить картинку в background-image через импорт

Рейтинг: 0Ответов: 1Опубликовано: 21.07.2023

Есть компонент на Vue, где у меня импортированы картинки:

<script setup>
import backgroundDesktop from "./../assets/images/bg-shorten-desktop.svg";
import backgroundMobile from "./../assets/images/bg-shorten-mobile.svg";
</script>

<template>
  <div class="shorter">
    <input type="text" class="shorter__input">
    <button class="shorten__button">Shorten It!</button>
  </div>
</template>

<style scoped lang="scss">
@import "./../assets/colors/color.scss";

.shorter {
    width: 80%;
    height: 150px;
    background-color: $darkViolet;
    margin: 0 auto;
    background-image: url('./../assets/images/bg-shorten-desktop.svg');
}
</style>

Для примера, в background-image я задал url той же картинки, которая отображается на сайте. Как мне это сделать через импорт? Тоесть чтобы путь в url был backgroundDesktop, который импортировал.

Ответы

▲ 0

Заводим в корне переменную --background-image

:root {
    --background-image: '';
}
.shorter {
    width: 80%;
    height: 150px;
    background-color: $darkViolet;
    margin: 0 auto;
    background-image: var(--background-image);
}

В нужном месте скриптом меняем её значение

document.querySelector(':root').style.setProperty('--background-image', "url('./../assets/images/bg-shorten-desktop.svg')");