Vue.js:无法为动态创建的HTML元素编译SASS样式

时间:2017-10-24 10:02:20

标签: javascript vue.js

我有一个简单的Vue.js组件,我在其中呈现一段HTML:

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

点击后,toggleButton()方法会更新button数据:

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

请注意<span></span>中的else元素。

发生了什么,我无法在我的组件中设置这个span元素的样式 - 大概是因为它是动态创建的:

<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>

父类(.sml-button)有其样式。孩子span没有。

如何在Vue.js组件内的动态添加的HTML元素上应用样式?

1 个答案:

答案 0 :(得分:1)

它在根组件和子组件中工作

<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>

这是更新子组件的更好,更清晰的方法。

&#13;
&#13;
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
    },
})
&#13;
.light-blue{
  color : #f00;
}
.light-green{
  color : #0f0;
}
&#13;
<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>
&#13;
&#13;
&#13;