I can't seem to find what I'm looking for with this. I'm running into an issue where I wish to bind a prop to a custom scss
variable.
I have the following "Card" component
:
<template>
<div class="option" v-bind:style="--optionBackground:url(img);" v-on:click="switchCards">
<div class="shadow"></div>
<div class="label">
<div class="icon">
<i class="fas fa-walking"></i>
</div>
<div class="info">
<div class="main">Blonkisoaz</div>
<div class="sub">Omuke trughte a otufta</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "Card",
props: {
img: String
},
methods: {
switchCards () {
console.log('clicked')
}
}
};
</script>
Ignore some of the placeholder scripts.
So, I'm trying to v-bind:style="--optionBackground:url(img);"
where img is passed in as a prop from the parent component
as follows:
<template>
<div id="app">
<div v-for="card) in cards" class="options" v-bind:key="card.id">
<Card v-bind:img="card.img"/>
</div>
</div>
</template>
<script>
import Card from "./components/Card.vue";
export default {
name: "app",
components: {
Card
},
data () {
return {
cards: [
{ id: 1, img: 'https://66.media.tumblr.com/8b69cdde47aa952e4176b4200052abf4/tumblr_o51p7mFFF21qho82wo1_1280.jpg'},
{ id: 2, img: 'https://66.media.tumblr.com/f19901f50b79604839ca761cd6d74748/tumblr_o65rohhkQL1qho82wo1_1280.jpg'},
{ id: 3, img: 'https://66.media.tumblr.com/8b69cdde47aa952e4176b4200052abf4/tumblr_o51p7mFFF21qho82wo1_1280.jpg'},
{ id: 4, img: 'https://66.media.tumblr.com/5516a22e0cdacaa85311ec3f8fd1e9ef/tumblr_o45jwvdsL11qho82wo1_1280.jpg'}
]
}
}
};
</script>
However, I'm receiving the following error:
invalid expression: Unexpected token : in
--optionBackground:url(img);
Raw expression: v-bind:style="--optionBackground:url(img);"
I've tried looking at as many use cases as possible, but I'm really not sure what to try next.
Couple of things.
You can't bind a SASS (aka SCSS) variable to the component, as SASS variables are resolved at compile time rather than run time. You can, however, bind a CSS variable (aka custom property), which is what you appear to actually want based on the variable name.
The syntax for using CSS variables is a little different than you have shown. What I suspect you want is
<div class="option" v-bind:style="{'--optionBackground': backgroundImage}">
and then define backgroundImage
as a computed property.
computed: {
backgroundImage() { return "url(" + this.img + ")"; }
}
(You can make the code more concise with template literals, but it looks like stack overflow doesn't handle those very well in answers.)
Edited to add: @boussadjira also correctly points out a typo in your code in the comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With