javascript - Vue.js 条件模块样式

标签 javascript css vue.js vuejs2

我想在模块中分离 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/

相关文章:

html - Coldfusion 80 标签模板

vue.js - Axios get 方法有网络错误和 Cors 策略,状态码为 200

html - CSS、HTML 中基本 LoopingSelector 的想法

javascript - 计算父级边距的 outerHeight

javascript - javascript 中 <a> 的 w3c 验证

javascript - Webpack 更改每个条目 block 的 output.filename

javascript - 如何获取 Vue.js 中选项更改事件的 <b-form-select> 元素的 id (BootstrapVue)

vue.js - 如何将上传的输入文件存储在 vue nuxt 应用程序的静态文件夹中?

javascript - 将数据从 AngularJs 服务传递到 Controller 以及 Controller 到 Controller

javascript - 如何让它等到一切完成直到下一次迭代