Apply CSS styles from a text area using v-html

I am currently working on developing a unique WYSIWYG application where users have the ability to write CSS in a textarea field and view its direct impact on the HTML content displayed on the page. As I was experimenting with different approaches, I attempted something similar to the following code snippet within my template:

<textarea v-bind="css"></textarea>
<style v-html="css"></style>

However, I encountered an error message stating: VueCompilerError: Tags with side effects (and) are ignored in client component templates.

Answer №1

Outdated answer, see below for an improved solution

Include a textarea with v-model:

<textarea v-model="css" />

Create a style tag in the onMounted hook:

onMounted(() => {
  const style = document.createElement("style");
  style.type = "text/css";
  updateCss(style, css.value);

  document.getElementsByTagName("head")[0].appendChild(style);

  el.value = style;
});

Remember to assign the style to 'el.value' so it can be accessed later.

Add a watch for changes in the input value:

watch(css, () => {
  updateCss(el.value, css.value);
});

The function 'updateCss' should look like this:

const updateCss = (el, css) => {
  if (el.styleSheet) {
    el.styleSheet.cssText = css.value;
  } else {
    el.innerHTML = "";
    el.appendChild(document.createTextNode(css));
  }
};

See a working demo here:

https://codesandbox.io/s/cocky-mestorf-uqz6f?file=/src/App.vue:246-463

Edit

A more efficient solution is available:

<template>
  <textarea v-model="css" />
  <component :is="'style'" type="text/css" v-text="css"></component>
</template>

<script>
import { ref } from "vue";
export default {
  setup() {
    const css = ref("body { background-color: blue; }");
    return { css };
  },
};
</script>

Using a component avoids errors related to the style tag:

<component :is="'style'">

Note that 'v-text' is used instead of 'v-html' as a safety precaution.

Check out the demo here: https://codesandbox.io/s/festive-germain-q9tg3?file=/src/App.vue:122-281

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

The issue of Nodejs Messenger broadcast message functionality being inoperative

Trying to initiate a broadcast through my Facebook Messenger bot, I have implemented the following code: if (subscribe === true) { // Initiate HTTP request to Messenger Platform request({ "uri": "https://graph.facebook.com/v2.11/me/broadcast_messa ...

Checking for any lint errors in all JavaScript files within the project package using JSHint

Currently, I am utilizing the gulp task runner to streamline my workflow. My goal is to implement JsHint for static code analysis. However, I have encountered a setback where I can only run one file at a time. Upon npm installation, "gulp-jshint": "~1.11. ...

Transferring a dynamic HTML file created using R's animation package onto a WordPress platform

After using the animation package in R to create an HTML file, I'm facing some challenges uploading it to my WordPress blog. It appears that additional js or css files may be required for proper functionality, but I'm uncertain about the process. ...

Align the text to the center within the Paper component using React and Material-ui

I've been struggling to center text inside a paper component in Material UI, and nothing seems to be working. I attempted using display:flex in the parent component with align-items:center in the child component. I also tried adding padding:5px for eq ...

Present the array elements in a format that allows the user to easily choose an option and explore the content

I'm currently working on a project where users will take a Computer Based Test and be graded on a selected subject. I have a database set up with questions and multiple choice options. My goal is to display the questions in a way that allows users to ...

A guide on how to efficiently retrieve all images stored in a specific directory

I attempted to showcase all the images from a single directory using jQuery, but unfortunately it is not functioning as expected. My folder setup includes an 'images' folder and a 'js' folder. I followed this question on Stack Overflow ...

Vue Tab doesn't properly initialize Vue Chart.js

In my component, I have two vue-tabs with two instances of vue-chart-js each. While they initialize without errors, attempting to extract an image from a chart in the inactive tab using document.querySelector('#mySecondChart').toDataURL() results ...

Array of JSON data passed in the request body

Recently, I have been attempting to pass JSON data to my req.body. The data structure is as follows: answers = ["A","B"]; //An array to be included in the JSON Object var Student_Answers = { //JSON object definition Answers: answers, matricNumber: ...

Alter Express routes automatically upon updating the CMS

Currently, I am working on a project that utilizes NextJS with Express for server-side routing. lib/routes/getPages const routes = require('next-routes')(); const getEntries = require('../helpers/getEntries'); module.exports = async ...

Sender receives a response from Socket.io

My goal is to have a socket respond only to the sender. Currently, I am working on having the user connect to the server using JavaScript when they visit any webpage. However, I am unsure whether the connection will be reset each time the user reloads th ...

Optimizing Require.js File for Efficient Loading

I have successfully implemented require.js with multiple individual files: require(['app/login/Login'], function (app) { new app.Login(); }); Everything is functioning as expected, with each module loading when needed. Recently, I have opti ...

Unable to link myxins with Quasar on a worldwide scale

Encountered an issue with an 'Undefined mixin' error while attempting to utilize a mixin in a Quasar project within a Docker container view image description here comments displayed on the screen here is the specific mixin included it in both t ...

jquery method for retrieving default value from dropdown list

When no option is selected from the dropdown list, I require the default value to be used for business logic purposes. ...

Unlinked Checkbox in Angular Bootstrap Modal Controller

I am currently utilizing the modal feature from Bootstrap 3's Angular fork, and I am facing an issue with using a checkbox within the modal and retrieving its value in my main controller. The checkbox value is properly bound in the view but not in th ...

Scrollspy in Twitter Bootstrap consistently highlights the final element

I'm struggling to understand why only the final section is being highlighted when scrolling. Can you help? <body data-spy="scroll" data-target="#homeToolbar" data-offset="50"> <nav class="navbar navbar-default navbar-fixed-top" id="homeToo ...

How can I conceal child <div> elements when the parent div is resized?

Struggling to implement a zoom in/out feature on my web app using the jqueryUI slider. Having trouble handling cases where the parent div shrinks too much, causing issues with the child containers. <div class="puck originator inline-block" style="w ...

Guide to capturing and playing audio on iOS6 with HTML5

Our team is currently working on a web application using HTML5 and Javascript. We are facing a challenge with implementing voice recording functionality, as the Wami Api we tried is not compatible with iPad due to its use of flash for recording. Could yo ...

Using NPM imports within a Node-RED node: A step-by-step guide

Is there a way to utilize NPM for handling dependencies in a Node-RED node instead of embedding the files directly into the packaged node? How can I set up a node so that it can leverage NPM to fetch package dependencies? ...

Execute the component function located within one page using another page

Can someone help me understand how to trigger OnSwipe from inside a different JS file named CardFooter.js? This file contains a button with an OnClick event that triggers OnSwipe from the preceding JS file called CardItem.js. Both of these files are includ ...

What is the process of extracting data from a variable and inserting it into a JSON object in JavaScript?

I have just started learning about JSON and am currently working on a JavaScript program. I've been searching for a straightforward solution, but I may not be framing my question correctly. My goal is to allow users to input their information which w ...