Tips for transforming a style object into a compiled attribute value using Vue API

Can the Vue 2.x API be used to convert an object representing component styles into a format suitable for the style DOM attribute? Essentially, I am seeking an imperative API similar to the v-bind:style directive.

For instance:

const style = {
    fontSize: '14px',
    color: 'red'
}

const value = Vue.createStyle(style) // font-size: 14px; color: red

I understand about the template compiler, scoped styles, risks of injecting user-provided styles, and the availability of v-bind. My goal is to supply a style string to an element within an inline frame using a computed property.

Although I believe it may not be significant, just in case, I am utilizing a payment processor SDK that embeds payment information in an inline frame to reduce PCI scope requirements. The SDK offers a function to set the inline style attribute of one or more fields within the frame.

Answer №1

If you want to customize your button style, you can follow these steps:

<button :style="customStyles">Click me</button>

In your computed properties section, define the custom styles like this:

computed: {
    customStyles() {
      return {
        '--bg-color': this.backgroundColor,
        '--height': this.buttonHeight + 'px'
      }
    }
  }

Finally, apply these variables to your button styling using CSS:

<style scoped>
button {
  background-color: var(--bg-color);
  height: var(--height);
}
</style>

Answer №2

Is the style converter in Vue accessible to the public? While one could potentially utilize a workaround with :style="myStyle", a watcher, and a ref, it might be better to create a custom reducer as shown below. This approach is likely to be more reliable than relying on an internal Vue method that could undergo name changes in future releases.

const style = {
  fontSize: '14px',
  color: 'blue',
  padding: '12px',
  border: '1px dotted red',
  borderRadius: '6px',
  borderRadiusTopLeft: '0'
}

/**
 * @param Object style
 * @return String inline style string
 */
function styleConverter(style) {
  return Object.entries(style).reduce(
    (acc, [key, value]) => {
      const convertedKey = key.replace(/[A-Z]/g, match => {
        return `-${match.toLowerCase()}`;
      });
      
      acc.push(`${convertedKey}: ${value}`);
      
      return acc;
    },
    []
  ).join('; ');
}

console.log(styleConverter(style));

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

As the cursor moves, the image follows along and rotates in sync with its

Can anyone help me figure out how to create a moving image that follows the mouse cursor? I have a radial pie menu with an image in the middle, and I want it to spin and rotate as the mouse moves. Any ideas on how I can achieve this effect? I would greatl ...

Custom Tooltips arrow is not receiving the CSS styling

I have implemented ReactTooltip from the ReactTooltip library You can view an example here Component Setup <ReactTooltip className={styles.customTheme} id={id} place={placement} effect="solid"> {children} </ReactTooltip> Stylin ...

Exploring the capabilities of Socket.IO in Node.js for establishing a connection with an external server

Background: My localhost (referred to as Server A) hosts a node.js server, while an external server running node.js can be found at (known as Server B). Although I lack control or access over Server B, which serves as a dashboard site for an IoT device in ...

Bootstrap is causing issues with unidentified div elements

I recently embarked on creating a slideshow using HTML, CSS, and jQuery. After completing the slideshow, I decided to add an interactive page beneath it. To streamline the layout process, I opted to utilize Bootstrap. However, upon loading Bootstrap, I en ...

Create type definitions for React components in JavaScript that utilize the `prop-types` library

Exploring a component structure, we have: import PropTypes from 'prop-types'; import React from 'react'; export default class Tooltip extends React.Component { static propTypes = { /** * Some children components */ ...

An API built with Mongoose, Express, and Node.js is currently only able to send a single image

I have a buffer array that needs to be converted into images and sent to the user. The issue is that the current code only sends one image: const express = require("express"); const asyncHandler = require("express-async-handler"); const ...

Innovative Features in Google Chrome

There is a nifty effect on Google Chrome that makes tabs light up when new content appears on the page and you are not currently viewing that tab. It can often be seen on sites like grooveshark. If anyone knows how to recreate this effect, I would greatl ...

Struggling with implementing ng-repeat in AngularJS for displaying HTML content

I stumbled upon a post that covers pretty much what I'm trying to achieve: AngularJS - Is it possible to use ng-repeat to render HTML values? Currently, the code appears like this and displays correctly as text: <div ng-repeat="item in items.Item ...

Error encountered during installation of Vuetify in Nuxt: "npm err! [email protected] install: `node build.js || nodejs build.js`"

After creating a Nuxt app using npx create-nuxt-app when running the dev server with npm run dev, I encountered the following error: ╭─────────────────────────────────────── ...

No data is being retrieved by SWR

I'm struggling to make SWR work in my code. Despite trying multiple examples, I can't seem to get it functioning properly. It's frustrating because the code looks fine and should work. I feel like I must be missing something simple. Current ...

Trigger an alert box using JavaScript after a successful submission

PHP Script Explanation The following PHP script is executed once the corresponding form has been filled out: <?php $connect = mysql_connect($h, $u, $p) or die ("Connection Failed."); mysql_select_db($db); ## Prevent SQL Inje ...

What is the correct way to pass the res object into the callback function of a jest mock function?

Currently, I am working on developing a web server using Node.js and am in the process of ensuring comprehensive test coverage with Jest. One specific function, logout, requires testing within the if statement where it checks for errors. // app.js functio ...

Is it possible to incorporate a Node.js library into an HTML document?

I am working on an HTML file where I want to incorporate the nodemailer library to handle email sending. Although in nodejs, I can easily include var nodemailer = require('nodemailer') at the beginning of the script section of my HTML file, it ap ...

Angular Logout does not reset local storage items

My ng-click logout function in the view: <div class="navbar navbar-default"><div class="container"> <div id="navbar-main"> <ul class="nav navbar-nav"> <li><a href="/">Home</a></li> <li ng-show=" ...

Convert a JSON weather report to a JavaScript timestamp for time conversion

When retrieving weather data from forecast.io in JSON format, there is a timestamp included: time:1445767494,"summary":"صافِ","icon":"clear-day","precipIntensity":0,"precipProbability":0,"temperature":32.99,"apparentTemperature":31.41,"dewPoint":10.5 ...

Currently, I am attempting to retrieve text input through the use of AngularJS

Having trouble retrieving text input values using Angular JS? The console keeps showing undefined. <div ng-controller="favouritesController" class="col-xs-12 favList"> <input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-1 ...

Angular - a simple method to determine the number of non-empty inputs in a complex template-driven form

As I work on multiple substantial Angular 11 template forms containing basic inputs like text, radiolists, and checkboxes, I am looking for the most effective method to calculate the percentage of completed inputs while the user is actively engaging with ...

Retrieve the value of [routerLinkActive] in the component's class

Recently, I've been working on a tab component called TabComponent and it includes the following HTML template: <a [routerLink]='link' [routerLinkActive]="[is-active]">link label</a> <button>Close tab</button> The c ...

Discovering appropriate variable names within Vue components

I need to find all occurrences of specific variable names within my Vue components. I have a list of variables in my program and I want to check which components each variable is being used in. Here's an example: let x = ['test_one', &apos ...

Error message: "Error occurred due to the undefined object in React UseEffect and

In my ClientData.js file, I am utilizing the useEffect hook to initiate an API call, which is functioning as intended. Subsequently, I am using useState to assign the response data from the API to a variable, which is also working properly. The retrieved ...