我想在模块中分离 Vue.js 组件中的样式。 每个样式模块将不仅仅是一个类,而且会定期添加新类。因此,很难更改整个组件的模板。所以,我正在寻找更实用的解决方案。
我想到了在样式中使用 v-if,但不确定它应该如何实现,或者这样的事情是否可行。
如果仅根据随 Prop 发送的名称,整个样式都会发生变化,那将更加实用。
<template>
<div class="color-text">
Text in the color of the class with just the name
</div>
</template>
<script>
export default {
name: 'comp',
props: ['name']
}
</script>
<!-- General styles -->
<style scoped>
div{
float: right;
}
</style>
<!-- red styles -->
<style module v-if="name === 'red'">
.color-text{
color: red;
}
</style>
<!-- blue styles -->
<style module v-if="name === 'blue'">
.color-text{
color: blue;
}
</style>
<!-- green styles -->
<style module v-if="name === 'green'">
.color-text{
color: green;
}
</style>
最佳答案
如果我要解决这个问题,我会使用传递类值。根本不用担心 Prop 。
<template>
<div class="color-text">
Text in the color of the class with just the name
</div>
</template>
<script>
export default {
name: 'comp'
}
</script>
<!-- General styles -->
<style scoped>
div{
float: right;
}
.red .color-text{
color: red;
}
.blue .color-text{
color: blue;
}
.green .color-text{
color: green;
}
</style>
然后你可以使用类属性传入你的颜色类型
<div id="app">
<comp class="red"></comp>
<comp class="green"></comp>
<comp class="blue"></comp>
</div>
我整理了一个示例 jsfiddle尽管在作用域样式和 webpack 如何处理注入(inject)方面可能需要一些调整
关于javascript - Vue.js 条件模块样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46224529/