Reputation: 7307
A plugin I use creates dynamic html and I want to add a dynamic background-color
using a hex passed via props.
This is the html in my component
<template>
<div class="pagination" slot="pagination"></div>
</template>
Generates dynamic HTML of this
<div class="pagination" slot="pagination">
<span class="swiper-pagination-bullet"></span>
<span class="swiper-pagination-bullet"></span>
</div>
The components receives props
props: ['primaryBgColor']
I can obviously see the color in the template if I write
<template>
<div>
{{ this.primaryBgColor }}
</div>
</template>
However when I write a style within the component like
<style>
.swiper-pagination-bullet {
background-color: {{ this.primaryBgColor }}
}
</style>
Webpack returns an error saying I have a CSS syntax error. Any ideas?
Upvotes: 0
Views: 724
Reputation: 2398
In your template, you can directly inject style
<template>
<div :style="this.primaryBgColor">
{{ this.primaryBgColor }}
</div>
</template>
primaryBgColor should contain object like {'background':"#cccc"}
For more option, vuejs had superb documentation. you can refer https://v2.vuejs.org/v2/guide/class-and-style.html#Object-Syntax-1
We can query the element and apply style like as follows
mounted: function () {
var elems = document.querySelectorAll('.swiper-pagination-bullet ')
var index = 0
var length = elems.length
for (; index < length; index++) {
elems[index].style.backgroundColor = this.primaryBgColor
}
},
Upvotes: 1
Reputation: 1104
suresh's answer may not work as it listens to the Vue mounted event, but by the time Vue component mounted, the plugin element may not yet be been injected.
if the plugin provides a similar event, you can register the handler there. if not, you can listen to the outer dom element using MutationObserver instead.
<template>
<div id="outer">
</div>
</template>
<script>
const observer = new MutationObserver(mutations => {
// suresh's function here
});
observer.observe(document.getElementById('outer'), { childList: true });
</script>
Upvotes: 1