Reputation: 413
I want to implement something very simple here, something in CSS:
.p {
color: /*something from javascript logic*/;
}
By checking the VueJS document, there is one way to achieve this by Style binding:
<p :style="{color:/*something from javascript*/}"> ... </p>
However, to do so, it means that I need to add every p tag such line, and it's not really a good solution.
What I want, is just like the beginning of the question, write something like
.p {
color: {{mycolor}};
}
So that I can do it once, apply everywhere.
Is there a neat way to do this? Namely apply a class selector in VueJS style binding? Thank you very much!
Upvotes: 1
Views: 1535
Reputation: 135752
There's no standard way of doing it in Vue.
There's a workaround/solution, though, which is just a custom component (say <v-style>
or whatever you choose to name it), so it's as reusable as any other component, and all of Vue's goods -- like v-if
-- can be used on its tag. Here's how it'd look:
Vue.component('v-style', {
render: function (createElement) {
return createElement('style', this.$slots.default)
}
});
// demo usage, check the template
new Vue({
el: '#app',
data: {
myColor: 'red'
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app" class="stuff">
<v-style>
.p {
color: {{myColor}};
}
</v-style>
<div class="p">
Remove "red" and type "yellow":
<input class="setting" type="text" v-model="myColor">
</div>
</div>
Caveats: the styles generated will be there only as long as the component is!
Another minor drawback is that since the name of the tag is <v-style>
(or whatever you chose to call it) and not <style>
, the IDEs may not color it nicely. But otherwise it'll just be like a regular <style>
tag.
Upvotes: 3