lesssugar
lesssugar

Reputation: 16181

Vue.js: Can't compile SASS styles for a dynamically-created HTML element

I have a simple Vue.js component in which I render a piece of HTML:

...
<div class="sml-button" v-on:click="toggleButton()" v-html="button"></div>
...

On click, the toggleButton() method updates the button data:

toggleButton: function() {
    if (this.shouldBeShown) {
        this.button = 'show less';
    } else {
        this.button = '<span>...</span>show more';    
    }
}

Notice the <span></span> element in the else.

What is happening, is I am unable to style this span element within my component - presumably because it's dynamically created:

<style lang="sass" scoped>
    .sml-button {
        color: #4390ca;
        font-size: 14px;
        font-family: latoregular, Helvetica, Arial, sans-serif;
        span {
            color: #3f3f3f; /* THIS WON'T BE COMPILED */
        }
    }
</style>

The parent class (.sml-button) has its styles. The child span doesn't.

How do I apply styles on a dynamically added HTML element inside of a Vue.js component?

Upvotes: 0

Views: 54

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34914

Its working in root component and child component both

<template>
  <template v-if="childDataLoaded">
    <child-cmp :value="childdata"></child-cmp>
  </template>
</template>

<script>
  export default{
    data(){
        childDataLoaded: false,
        childdata : [];
     },
     methods:{
      fetchINitData(){
        //fetch from server then
         this.childdata = res.data.items;
         this.childDataLoaded = true;
         console.log(res.data.items) //has some values
       }
     }
   components:{
     childcmp
    },
   mounted(){
     this.fetchINitData();
     }
    }
 </script>

Here is the Nice and cleaner way to update child component.

var child = Vue.extend({
    template: "<div>Child Component : <span class='light-blue'>My dynamicHTML</span></div>"
});
var app = new Vue({
    el: "#vue-instance",
    data: {
        dynamicHTML:"Root Component : <span class='light-blue'>My dynamicHTML</span>"
    },
    methods : {
      changeHTML: function(){
        this.dynamicHTML = "Root Component Changed : <span class='light-green'>My dynamicHTML</span>"
      }
    },
    components: {
        child
    },
})
.light-blue{
  color : #f00;
}
.light-green{
  color : #0f0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.1/vue.js"></script>
<div id="vue-instance">
    <div v-html="dynamicHTML"></div>
    <child></child>
    <button v-on:click="changeHTML">Change HTML</button>
</div>

Upvotes: 1

Related Questions