Joshua
Joshua

Reputation: 11

Dynamically change <style> inside a Single File Component

Is it possible to dynamically change the content of a scoped inside a Single File Component?

Upvotes: 1

Views: 4053

Answers (2)

skribe
skribe

Reputation: 3615

You could do it using the v-html directive.

Since I don't know your actual code I will just give you the code for a basic proof of concept.

In the template...

<template>
   <div>
      <head v-html="styles"></head>
      <div class="test">
         <p>change this paragraph</p>
      </div>
   <textarea name="" id="" cols="30" rows="10" v-model="csscode"> </textarea>
   </div>
</template>

In the script...

<script>
export default {
    data() {
        return{
           csscode: null,
           styles: null,
        }
    },
     watch:{
        csscode(val){
            this.styles = '<style>' + val + '</style>';
        }
    }
 }
</script>

Upvotes: 2

Onur &#214;zkan
Onur &#214;zkan

Reputation: 1018

Inside style tag, no. Its not possible because of build extracts a .css file.

But as an alternative you can use javascript object as an style object.

var app = new Vue({
  el: '#app',
  data: function(){
    return {
      textAreaStyle: {border: '2px solid blue', color: 'red', width: '500px', height: '300px'}
    }
  },
  methods: {
    updateStyle (event) {
      this.$set(this.$data, 'textAreaStyle', JSON.parse(event.target.value));
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
  <textarea :style="textAreaStyle" @change="updateStyle">{{textAreaStyle}}</textarea>
</div>

Upvotes: 0

Related Questions