Vue 组件 - 为深度注入的 HTML 内容动态创建样式

问题描述 投票:0回答:1

我们拥有用户使用文本编辑器创建的内容,该编辑器为他们创建 HTML 标签,例如

h1
p
等。

我们还让用户通过预定义的表单定义主题,该表单基本上为这些标签设置样式对象。

在 Vue 中,您可以轻松地将它们添加为

<h1 :style="headingTheme"></h1>
属性,但是 仅当 Vue 创建这些标签时。

但是,此 HTML 会作为字符串动态注入到组件中。

目前,我们必须在

<style>
标签中创建一个类,将每个属性单独绑定到主题对象,如下所示..

<style lang="scss" scoped>

 .my_parent_class:deep(h1) {
   color: v-bind('headingTheme.color');
   font-family: v-bind('headingTheme.fontFamily');
   ... more properties here ....
 } 
    
</style>

但是我们必须记住每次更改主题选项时都要更新它。

有没有办法动态构建这个css样式并将其应用到Vue组件中?

可以使用

new CSSStyleSheet()
,并即时制作一张纸,但它很麻烦。

我想知道是否还有其他

Vue
方式?

类似于

:style="themeStyle"
绑定,但有些如何级联到任何不受 Vue 管理的子节点!!

vue.js vuejs3 vue-component
1个回答
0
投票

只需编译您的 HTML:

VUE SFC 游乐场

<script setup>
import { reactive, compile, ref } from '@vue'

const headingTheme = reactive({
  color: 'red',
  'letter-spacing': '5px'
});

const html = ref('<h1 :style="headingTheme">Hello world!</h1>');

</script>

<template>
  <component :is="compile(html)" :="{headingTheme}"/>
</template>
© www.soinside.com 2019 - 2024. All rights reserved.