Tips for designing a unique style attribute for your Vue.js component

My goal is to utilize Vue.js without the need for a build step, but I've encountered an issue with its lack of a style property.

To tackle this problem, I came up with the idea of creating a custom "style" property on my Vue component instance and dynamically injecting its content into the DOM upon component creation or mounting.

The challenge lies in figuring out how to implement this concept. After exploring the plugins documentation, I realized that I would likely need to develop a plugin that checks for the existence of a "style" property and inserts it into the DOM accordingly. Additionally, I prefer not to use the Vue.component() function as I aim to leverage ES6 import/export. Here's a visualization of the expected outcome:

// MyComponent.js
export default {
  template: `<div>My component</div>`,

  style: `
    .hello {
      background: #ccc;
    }
  `,
}

// App.js
import MyComponent from './MyComponent.js'

new Vue({
  el: '#app',

  components: {
    MyComponent
  }
})

Upon the creation of MyComponent, it should extract the value of the "style" property and incorporate it into the DOM, similar to the following approach. Any suggestions on how to achieve this are highly appreciated.

$('body').append('<style>' + STYLE + '</style>')

Included here is a reference to a plugin utilizing the Vue.component() function, which I'd prefer to avoid:

https://github.com/NxtChg/pieces/tree/master/js/vue/vue-css

Answer №1

To incorporate inline styles in your project, utilize v-bind:style or simply :style. This will appropriately apply the object's properties as CSS styles. Remember to use camelCase, such as backgroundColor instead of background-color.

If you require a global style, insert a style tag into the head using the mounted life-cycle hook. Ensure removal in destroyed.

UPDATE: My previous response was incorrect, please find the revised answer below

var app = new Vue({
  el: '#app',
  data: {
    subject: 'World'
  },
  computed: {
    subjectStyle() {
      return {
        color: 'yellow',
        backgroundColor: 'rebeccapurple',
      };
    }
  },
  mounted() {
    const css = `
      body {
        background-color: #eee;
        font-family: 'Comic Sans MS', sans-serif;
      }
    `;
    this.styleTag = document.createElement('style');
    this.styleTag.appendChild(document.createTextNode(css));
    document.head.appendChild(this.styleTag);
  },
  destroyed() {
    this.styleTag.remove();
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  Hello, <span :style="subjectStyle">{{ subject }}</span>!
</div>

Below is plugin code that allows each Vue instance to specify styling, which will be injected and removed from <head> accordingly.

const StylePlugin = {
  install(Vue) {
    Vue.mixin({
      mounted() {
        const css = this.$options.style;
        if (!css) return;
        this.$styleTag = document.createElement('style');
        this.$styleTag.appendChild(document.createTextNode(css));
        document.head.appendChild(this.$styleTag);
      },
      destroyed() {
        if (this.$styleTag) {
          this.$styleTag.remove();
        }
      }
    });
  }
};

Vue.use(StylePlugin);

var app = new Vue({
  el: '#app',
  data: {
    subject: 'World'
  },
  style: `
    body {
      background-color: rebeccapurple;
      color: white;
      font-family: 'Comic Sans MS', sans-serif;
    }
  `,
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  Hello, World
</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

Using HTML and JavaScript to verify email addresses

I have been working on an "Email Validation" code, but it seems to be malfunctioning. I can't figure out why. Would you mind taking a look at it? Thank you. I suspect that the issue lies with this line document.getElementById("custEmail").onchange = ...

Deleting a sentence from a text document

Is there a way to remove a row from a text file without leaving empty lines? See the Example and Example2. Consider this scenario: Hello Hello2 String After deletion, the file should look like this: Hello Hello2 I attempted the following code but it re ...

Displaying a JQuery notification when hovering over a link

I am having trouble getting an alert to pop up when I hover over a hyperlink using JQuery and Javascript. The hyperlink is inside an anchor within the main section of the HTML. Any assistance would be much appreciated. Here is my current code snippet: &l ...

How can I clear my object so that new Dates() can be added to my calendar?

I am working on updating my program to seamlessly replace old JSON data from a holidays API with new data as soon as it is received. Initially, I attempted to declare the array as empty at the start, but this approach did not yield the desired results. Si ...

When data is submitted through the POST method, it mysteriously disappears

When I send the "user" variable to another page called Survey.php, here's how it looks: In the index.html file: <form action="Survey.php" method="post" name="frm"> <div><input type="text" name= ...

What is the best way to interact with Redis without using any external modules?

I am curious about the communication process between the node redis wrapper and the RESP (REdis Serialization Protocol) database. Here is a simple example: const redis = function(uri) { this.client = '' // How do we establish a connection wit ...

Learning how to allocate a key index within an array using Vue.js

Hey there! I've got a form set up like this: <tr v-for="(post, index) in posts" v-bind:index="index"> <td>{{ post.rut }}</td> <td>{{ post.names }} {{ post.father_lastname }} {{ post.mother_lastname }}& ...

Maintain query parameters in Angular6 while routing with canActivate

When using Auth guard to verify login status and redirecting to the login page if a user is not logged in, there seems to be an issue with losing all query parameters during the redirection process. I attempted to preserve the query params by adding { qu ...

Unraveling the mysteries of this PHP-generated object

Need help with iterating over a JSON object generated by PHP code in response to a web service request. Looking for guidance on rendering sub-objects in a select list, especially those with value indexes. Can someone provide assistance on populating a sel ...

Is it possible to dynamically load a component in a Nuxt / Vue app based on the domain?

I'm facing a challenge with my system where I need to load a unique dynamic Vue component based on the incoming domain name. While I can identify the host in a middleware function using the context parameter, I'm unsure of how to access the incom ...

Ending the loop of a jQuery JSON array when reaching the final row

I have a function that retrieves a JSON array and shows the results as a list with ten items. However, if there are fewer than ten results, it starts over from the beginning. This is my code: $.ajax({ url: 'http://www.entertainmentcocktail.com/c ...

Using Vue.js with jQuery plugins: A step-by-step guide

Currently in the process of rewriting code to Vue.js, I am interested in incorporating some Jquery plugins, but I am uncertain about the correct method. One plugin I would like to utilize is a scrollbar: I understand that initialization should look someth ...

JavaScript doesn't pause for the data to come back, resulting in an undefined value

When I call the function "classTableData" on a button click, my allData variable becomes undefined. The problem seems to be that it processes the next line of code without waiting for the results, causing allData to remain empty. Can anyone provide some ...

Customizing BootstrapVue styles by overriding default Bootstrap styles: encountering an error due to undefined variable

I recently set up a new Vue application and integrated Bootstrap-Vue for styling, but I'm encountering difficulties when trying to customize Bootstrap's default style. Error message: [sass] Undefined variable. 11 │ $b-custom-control-indicator- ...

Issues with excessive firing of JQuery blur and hide functions

I am currently using jQuery v1.11.2 and have set up a basic JSFiddle at this link (http://jsfiddle.net/k1g3upbv/). The layout may not be ideal in JSFiddle due to the integration of Twitter Bootstrap within my project. I quickly put together the JSFiddle, o ...

Tips for customizing the color of Menu in material-ui v5

I've been searching for solutions to change the background color of the Menu, but the methods I found are outdated. The use of @mui/styles and makeStyles is now deprecated, as stated in mui.com/styles/basics/#hook-api. I attempted to change the backgr ...

Get a reference to pass as an injection into a child component using Vue js

Is there a way to pass a reference to child components? For example: The Parent component provides the ref: <template> <div ref="myRef" /> </template> <script> export default { name: 'SearchContainer', pr ...

encountering a problem with retrieving the result of a DOM display

private scores = [] private highestScore: number private studentStanding private studentInformation: any[] = [ { "name": "rajiv", "marks": { "Maths": 18, "English": 21, "Science": 45 }, "rollNumber": "KV2017-5A2" }, { "n ...

The ReactJS input box is stubbornly rejecting all input

Struggling with this code and can't seem to figure out why the input lines aren't accepting anything. After searching extensively, I decided it was time to ask for help. P.S. I am new to react class App extends React.Component { state = { inp ...

Is it possible to target elements based on a specific CSS3 property they use?

Is there a method to target all elements in the DOM with a border-radius other than 0? If anyone has suggestions, it would be greatly appreciated! ...