Issue in Vue.js: Struggling to compile SASS styles for an HTML element generated dynamically

I'm working with a basic Vue.js component where I'm rendering a snippet of HTML:

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

When the button is clicked, the toggleButton() function updates the button data:

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

Take note of the <span></span> element in the else condition.

The issue I'm facing is that I can't style this dynamically created span element within my component:

<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, while the child span does not.

How can I apply styles to a dynamically added HTML element inside a Vue.js component?

Answer №1

It is functioning in both the root component and child component.

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

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

Here is a more elegant and tidy method to update the 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React is struggling to dynamically update text content using button click events

As a beginner in the world of React, Nodejs, and JavaScript, I am exploring onClick events to dynamically change text by clicking buttons. In my practice project, I have an input type="checkbox" that toggles the text between bold and normal style ...

Is the 'wait > remaining' condition ever satisfied in the throttle function of underscore.js?

Check out the library code at line 860: https://github.com/jashkenas/underscore/blob/master/underscore.js if (remaining <= 0 || remaining > wait) Under what circumstance would the second part of this statement be true? Background - This is my firs ...

Challenges with sending JSON encoded Arrays from WordPress to PHP results in empty or NULL responses

My Plugins site has multiple Inputs that I need to gather values from and push them into an array. Then, I utilize the jQuery.post method to send this data to my PHP script. Javascript: var json = JSON.stringify(output); // output is an array with multip ...

Best practices for alerting using React and Redux

As I delve into Redux for the first time and work on revamping a fairly intricate ReactJS application using Redux, I've decided to create a "feature" for handling notifications. This feature will involve managing a slice of state with various properti ...

Create a custom Android home screen widget using JavaScript or another programming language

I have a project in mind to create an Android App and include a home-screen widget. While I know it can be done with Native Android, my preference is to use JavaScript for development. Would anyone happen to know of any other solutions that allow the use ...

What are the steps to transform a blob into an xlsx or csv file?

An interesting feature of the application is the ability to download files in various formats such as xlsx, csv, and dat. To implement this, I have utilized a library called fileSaver.js. While everything works smoothly for the dat/csv format, there seems ...

Modify meta titles according to specific url #id

My website is built in static HTML and our server does not support PHP or C#. Can JavaScript, jQuery, Ajax, or other technologies achieve the following: If the URL is: Https://example.com/page, the meta title will display as "home page". Https://example ...

Choose a specific <div> element from an external page using Ajax/PHP

I'm encountering a small issue. I am currently utilizing Ajax to dynamically load content from another page into a <div> element after detecting a change in a <select>. However, my specific requirement is to only load a particular <div& ...

Trying to configure and use two joysticks at the same time using touch events

I have been grappling with this problem for the past two days. My current project involves using an HTML5/JS game engine called ImpactJS, and I came across a helpful plugin designed to create joystick touch zones for mobile devices. The basic concept is th ...

Angular does not update the progress bar

Imagine having a component html with your own customized round progress bar <round-progress #progress [current]="current" </round-progress> The "Current" value represents the percentage. In my TypeScript component, I have written: ...

Troubleshooting Subtle Validation (on the front end)

After implementing unobtrusive validation, I noticed that my form appears error-free upon initial inspection. However, when I execute the following code: $(valForm).valid(); The result returned is false. To troubleshoot this issue, I want to determine ...

Troubleshooting problem with cookies in express-session

I've been working on an app with express.js and vue 3, incorporating session-based authentication. While everything functions perfectly locally, I've encountered issues when trying to deploy to production. Here's a snippet of the code where ...

Using the v-for directive before applying the Vue directive

I need help with displaying images in a carousel from data fetched via Firebase. I have created a directive, but the problem lies with the v-for loop. The directive is executed before the v-for loop, resulting in no items in the carousel. Directive: di ...

Explain the inner workings of the setTimeout() function in JavaScript

My goal is to create a line in my code by placing points according to the line equation and adding a 100 millisecond delay before each point is displayed. However, when I try to run the code, it seems to wait for some time and then displays all the points ...

How can I retrieve the updated input value once a specific key has been pressed in the prototype?

After a customer presses any key, I would like to check an email. Below is the code I am using: document.observe("dom:loaded", function() { $('billing:email').observe('keypress', function(event){ console.log(event.element(). ...

React-querybuilder experiencing issues with validator functionality

While utilizing the react-querybuilder, I have encountered an issue with field validation not functioning correctly. Upon reviewing this StackBlitz, it appears that when clicking on Rule and checking all fields, there are no errors present. export const fi ...

Is it possible to incorporate an additional value into the jQuery widget 'Autocomplete' by using a second variable?

For several years, I have been utilizing the jQuery 'Autocomplete Widget' in my projects. This plugin allows me to pass a value labeled as 'term' to the PHP SQL code that works like this: $( "#cs1" ).autocomplete({ aut ...

implement a data update feature in a Vue application using methods and Axios to manipulate

I am having trouble displaying data on a graph in my web interface using Vue js. I am fetching data from the backend to the frontend with axios, and although I can display an empty graph, the passed data is not showing up. Can someone please help me iden ...

Bug in Async.js causes unexpected results in loop involving numbers

When attempting to reference a variable in a for loop using the Async Library for Node.js, it seems to not work as expected. Here is an example: var functionArray = [] , x; for(x = 0; x < 5; x++) { functionArray.push(function (callback) { conso ...

What is the best way to sort a combination of numbers and text strings?

Within my table, I have column names enclosed in <th> tags and only numerical values inside <td> tags. When the user clicks on a <th> tag, the sorting algorithm organizes the values in ascending or descending order. .sortElements(function ...