我有一個 Vue Js 應用程式(V2),其結構如下(縮短以關注問題):
_variables.scss
$brand-theme:#F5F5F5
并通過 sass 加載器加載,就像在 vue.config.js 中一樣
@import "@/assets/scss/_variables.scss";
因此,在我的各種 Vue 組件中,我可以像這樣參考(這在一些 Vue 檔案中使用,而不僅僅是 App.Vue 例如)
.button {
width: 100%;
text-align: center;
background: $brand-theme;
....
我有一個要求,我需要檢查 URL,并在渲染之前在運行時更改此值,例如通過操縱 dom 或其他有效方法。
經過一些初步研究,我發現使用這種當前結構存在問題,并導致我重新考慮該方法,但我很想知道是否有辦法以最少的代碼更改來做到這一點。
提前致謝。
uj5u.com熱心網友回復:
將值分配給#app元素上的 CSS 變數:
<style lang="scss">
#app {
--brand-theme: $brand-theme;
}
</style>
在任何組件中:
<style>
.button {
background-color: var(--brand-theme);
}
</style>
--brand-theme在運行時更改#app元素或其任何后代上的變數值,將影響該元素和任何正在閱讀的子元素var(--brand-theme)。
從 JS 更改 CSS 變數的值很容易:
document.querySelector('#app').style.setProperty('--brand-theme', newValue);
// or, on <div id="app" ref="myApp">
this.$refs['myApp'].style.setProperty('--brand-theme', newValue);
您還可以使用以下語法:
<div :style="{ '--brand-theme': dataDrivenValue }" />
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/444713.html
標籤:javascript css Vue.js Vuejs2 萨斯加载器
