js获取CSS/SCSS/LESS的常量
<template><div id="body"><p>--color: {
{ color }}</p><p>--width: {
{ width }}</p><p>--color_after: {
{ color_after }}</p><p>--width_after: {
{ width_after }}</p></div>
</template><script>
export default {data() {return { color: "", width: "", color_after: "", width_after: "" };},mounted() {var el = document.querySelector("#body");// 知识点:document.defaultView===window----------------------------------------var style = window.getComputedStyle(el) || document.defaultView.getComputedStyle(el); //js获取div样式this.color = style.getPropertyValue("--color");this.width = style.getPropertyValue("--width");var style_after = window.getComputedStyle(el, ":after") || document.defaultView.getComputedStyle(el, ":after"); //js获取伪类样式this.color_after = style_after.getPropertyValue("--color-after");this.width_after = style_after.getPropertyValue("--width-after");},
};
</script>
<style lang="scss" scoped>
#body {--color: red;--width: 100px;&:after {--color-after: blue;--width-after: 200px;}
}
</style>
打印效果
CSS/SCSS/LESS获取js的值(js主动推送参数给CSS使用)
<template><div id="body">如何通过js传输常量给css,共用js的常量值</div>
</template><script>
export default {mounted() {var el = document.querySelector("#body");el.style.setProperty("--color", "white"); //js往css传递参数el.style.setProperty("--background-color", "red"); //js往css传递参数},
};
</script>
<style lang="scss" scoped>
#body {color: var(--color);background-color: var(--background-color);
}
</style>
打印效果