Subscribe on changes!

style v-bind should have prepend "url(" and append ")" when the variable is an url/asset/module

avatar
Apr 19th 2023

What problem does this feature solve?

style v-bind should have prepend "url(" and append ")" when the variable is an url/asset/module

What does the proposed API look like?

<script lang="ts" setup>
import shape from "@/assets/shape.svg";
</script>
<style scoped lang=scss>
div {
    background-image: v-bind(shape);
}
</style>

since background-image: v-bind(shape); converts to var(--3d872d92-shape) and wrapping it with url is not allowed. the v-bind should set this scss variable --3d872d92-shape: url(/src/assets/shape.svg) instead of --3d872d92-shape: /src/assets/shape.svg.

avatar
Apr 19th 2023

I don't think we can reliably detect that this import is actually a valid asset string. So you will need to create the correct css url value yourself and bind that.

<script lang="ts" setup>
import shape from "@/assets/shape.svg";
const shapeUrl = `url(${shape})`
</script>
<style scoped lang=scss>
div {
    background-image: v-bind(shapeUrl);
}
</style>
avatar
Apr 20th 2023

That looks okay, perhaps this could be documented anywhere. Ik had issues finding anything about it

avatar
Apr 20th 2023

v-bind css 功能里面是可以写表达式的, 当你写backgroud-image的 时候是需要你自己添加 url() 函数 When using the 'v-bind css' function, expressions can be added. When using the 'background-image' property, it is necessary to manually add the 'url()' function.

<script setup>
import testjPG from './test.jpeg'
const bgUrl = 'https://pcm-30170.picsz.qpic.cn/product-test/20220927164754/5e9a0934aadc7543ba3c3cea2bc38a8d.jpg'
const fontSize=14
</script>

<style>
div {
   background-image: v-bind("`url('${testjPG}')`");
   background-image: v-bind("`url('${bgUrl}')`");
   font-size:v-bind("`${fontSize}px`")
}
</style>

你可以直接在v-bind中写表达式 就可以直接引入了 You can directly add expressions in 'v-bind' to import it directly 注意表达式中 "url('${bgUrl}')" 包裹${bgUrl}的单引号不能掉 Note that the single quotes wrapping ${bgUrl} could not be forget