vue.js - Pass Vuejs Data in Style (SFA)
问题描述
I have a beginner question. For example i have a componnent that have a Boolean prop. Deppending on the values of the prop i'm setting the path to which Less he should to take, but that doesn't work. Does anyone know how to do that? And if that is possible?
<template>
<div class="my-style">Text</div>
</template>
<script>
export default {
props: {
isFirstApp: Boolean,
},
data: function() {
return {
isFirst: true,
path: '',
}
}
created: function () {
if(this.isFirstApp){
this.path = '/styles/vars1.less';
}else{
this.path = '/oldstyles/vars2.less';
}
},
}
</script>
<style lang="less" scoped>
@import `${path}`;
.my-style {
color: @my-variable;
}
</style>
解决方案
It's a bit of a hack, but you can achieve this by creating scss-style variables in the element's style
and then using these in the actual style to set 'real' css properties. It works as the variables set in style are ignored by the browser as they are not valid css properties, but scss gets access to all previously set properties, and these appear as variables.
<template>
<div class="hello">
<!-- Set the style to include the values from cssVars computed property -->
<p :style="cssVars">Hello World</p>
<!-- type in a new color name/#rgb value to dynamically change it -->
<input v-model="color">
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String
},
data() {
return {
color: "red"
};
},
computed: {
// Return an object containing scss variables
cssVars() {
return {
"--color": this.color
};
}
}
};
</script>
<style scoped>
// Use the variables defined in style to set 'real' css properties
p {
color: var(--color);
}
</style>
推荐阅读
- c# - 列表框中的选定项不断返回 null
- angular - 没有 TypeScript 的 Angular 8 依赖注入?
- angular - Angular translate core - 从 http 请求更新翻译
- android - 按钮上不显示可绘制图标
- c - yylval 在 lex 和 yacc 中的作用
- python - 回归与分类可以解决的问题
- java - 将罐子(多个)添加到 maven 类路径会产生错误
- python - python3:从编译模式中提取IP地址
- python - 为什么线性回归只对一个特征起作用,而对另一个特征起作用
- unix - 如何在 UNIX 中删除特定列的空格