vuejs / vitepress

Vite & Vue powered static site generator.
https://vitepress.dev
MIT License
11.29k stars 1.83k forks source link

unable to bind a variable url to background-image #2472

Closed alephpi closed 8 months ago

alephpi commented 10 months ago

Discussed in https://github.com/vuejs/vitepress/discussions/2471

Originally posted by **alephpi** June 3, 2023 I have a assets of images ``` .vitepress |-theme |-assets |-wallpaper |-default.png |-components |-Home.vue ``` And in Home.vue, I want to bind a variable `bgImgUrl` to the `background-image` where const bgImgUrl = \`url('../assets/wallpaper/${title}.png')\` I tried `background-image: v-bind(bgImgUrl)`, but the image is not rendered. However If I just use `background-image: url('../assets/wallpaper/default.png')`, this works, but it will not be variable. I am really confused, by the way the inline binding doesn't work either. **I think the problem lies the entanglement of three things: url(), v-bind() and the url resolution specificity of vitepress, and I really don't know how to deal with them.**
userquin commented 10 months ago

have you tried to import the asset import bgImgUrl from '../assets/wallpaper/default.png?url? https://vitejs.dev/guide/assets.html#explicit-url-imports

alephpi commented 10 months ago

have you tried to import the asset import bgImgUrl from '../assets/wallpaper/default.png?url? https://vitejs.dev/guide/assets.html#explicit-url-imports

Not yet. But what I want is let bgImgUrl be a reactive variable (which can be modified), so that we can change the background image among multiple images in the wallpaper folder.

Or maybe I just import all the images directly and make an url dictionary? That way kinds of verbose since the wallpaper is really numerous.

Update: I tried direct import with background-image: url(--bgImgUrl) and background-image: v-bind(bgImgUrl), but still neither of them works.

alephpi commented 10 months ago

direct assignment: image

binding: image

seems that when binding it just cannot resolve the relative path

alephpi commented 10 months ago

current workaround: create static css rules for background-image, bind the css class to title. Seems the problem is the relative url resolution.

brc-dd commented 8 months ago

Dynamic variables won't work with imports/urls. Rollup needs to be able analyze them statically at build level to emit assets. It'd work if assets are in public directory. We can't fix this here.