如何使用Vue API将样式对象转换为已编译的属性值



是否可以使用Vue 2.x API将表示组件样式的对象编译为适合样式DOM属性的属性值?我正在有效地寻找类似于v-bind:style指令的命令式API。

例如:

const style = {
fontSize: '14px',
color: 'red'
}
const value = Vue.createStyle(style) // font-size: 14px; color: red

我知道模板编译器、作用域样式、用户提供的样式注入的危险、v-bind的存在等。我希望使用计算属性为嵌入内联框架中的元素提供样式字符串。

我不认为这是相关的,但以防万一,我正在使用一个支付处理器SDK,它将支付信息嵌入到内联框架中,以帮助最大限度地减少PCI范围要求,并且SDK提供了一个功能来设置嵌入框架中的一个或多个字段的内联样式属性。

您可以这样做:

<button :style="cssVars">My button</button>

然后在你计算的属性中,你会写:

computed: {
cssVars() {
return {
'--bg-color': this.bgColor,
'--height': this.height + 'px'
}
}
}

最后,在你的风格中使用这些变量:

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

我不确定Vue中的样式转换器是否面向公众。虽然使用:style="myStyle"(一个观察者和一个引用(可以做一些棘手的事情,但我只会考虑写我自己的reducer,如下所示。它应该比尝试使用可能在任何版本中更改名称的内部Vue方法稳定得多。

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));

最新更新