Home > Mobile >  Set content of vue 3 single file components' style tag
Set content of vue 3 single file components' style tag

Time:01-30

I need to present some random/dynamic html data in my project that might contain style tags, by default vue.js doesn't allow style tags in the template to avoid messing styles that is a very good option. To make my project work I tried some runtime-component projects on github but they doesn't accept css styles in the way I need, so I came up with the solution of creating my own runtime component with accepting css styles data. What I want in code is sth like:

<template>
  <div v-html="template"></div>
</template>

<script>
export default {
  name: "DynamicTemplate",
  props: {template: String, style: String}
}
</script>

<style scoped>
// style data goes here
</style>

Any alternative working solution is welcome too :)

I tried v-html and v-text attributes on the component style tag (without any results) and also using css @import statement with base64 encoded css codes (got some errors like Cannot read properties of undefined), but none of them worked :(

CodePudding user response:

Here is an example of passing that can pass dynamic HTML data in your project with an example using style tags

<template>
  <div>
    <div v-html="template" :style="style"></div>
  </div>
</template>

<script>
export default {
  name: 'DynamicTemplate',
  props: {
    template: {
      type: String,
      required: true
    },
    style: {
      type: Object,
      required: false,
      default: () => {}
    }
  }
}
</script>

Here is the component being used.

<DynamicTemplate
  :template="<p>This is some dynamic HTML content</p>"
  :style="{ color: 'red', font-size: '14px' }">
</DynamicTemplate>

CodePudding user response:

Here is an example of passing that can pass dynamic HTML data in your project with an example of passing classes dynamically

<template>
  <div>
    <div v-html="template" :></div>
  </div>
</template>

<script>
export default {
  name: 'DynamicTemplate',
  props: {
    template: {
      type: String,
      required: true
    },
    classes: {
      type: Object,
      required: false,
      default: () => {}
    }
  }
}
</script>

Here is the component being used.

<DynamicTemplate
  :template="template"
  :classes="classes"
/>

CodePudding user response:

You can encapsulate the data inside the style tags inside the component tag provided by vue in this manner ->

  <component :is="'style'"> .test-class { color: red; }....Your style data </component>

An example of the same can be found in this project I created

https://codesandbox.io/s/interesting-dewdney-id9erd?file=/src/components/HelloWorld.vue

  • Related