【问题标题】:How to set className dynamically?如何动态设置类名?
【发布时间】:2019-12-11 15:13:07
【问题描述】:

我有 Vue.js 应用程序,并且有一个组件,代码如下:

1) 在“模板”部分:

<panel
  :collapsible="true"
  title="Basic section"
  :iscollapsed="false"
  class="category-panel"
  :class="className"
>

2) 在“数据”部分:

className: '',

3) 在“方法”部分:

toggleColor () {
  if (!this.document.docDate) {
    this.className = 'panel >>> .panel-title-red'
  }
},
async save () {
  this.toggleColor()
  ...
}

4) 在“风格”部分:

.panel >>> .panel-title
  font-weight 400
.panel >>> .panel-title-red
  font-weight 400
  color red

面板标题使用“样式”部分的第一类,即面板标题的颜色为黑色。当我单击“保存”按钮时,我调用了 toggleColor 方法,在某些情况下我想将颜色更改为红色。它不能以这种方式工作。如何让它发挥作用?

【问题讨论】:

    标签: vuejs2


    【解决方案1】:

    大概你的标题在面板组件中有自己的元素。您将无法从面板外部直接向该元素添加 CSS 类,您只能向面板的外部元素添加类。要将类添加到内部元素,您需要在面板上公开一个合适的道具并让面板处理样式。

    但是,要使用与您在问题中的代码类似的代码使其工作,您需要更改此代码:

    this.className = 'panel >>> .panel-title-red'
    

    试图将类设置为选择器是没有意义的。相反,它应该是:

    this.className = 'panel-title-red'
    

    这会将panel-title-red 类放在面板的最外层元素上。这可能不是您想要的元素,但这是我们可以从面板外部做的最好的事情。然后,您需要合适的 CSS 才能使其生效:

    .panel-title-red >>> .panel-title
      font-weight 400
      color red
    

    我假设这将通过预处理器,因为它实际上不是有效的 CSS,但它与您发布的代码一致。

    【讨论】:

      【解决方案2】:

      您可以使用:class="{'your-class-name': isAllowed}" 模式设置className。

      <panel
        :collapsible="true"
        title="Basic section"
        :iscollapsed="false"
        class="category-panel"
        :class="{'panel-title-red': isColorToggled}"
      >
      ...
      // data
      isColorToggled : false,
      ...
      // methods
      toggleColor () {
        if (!this.document.docDate) {
          isColorToggled = true;
        }
      },
      

      【讨论】:

        猜你喜欢
        • 2018-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-12
        • 1970-01-01
        相关资源
        最近更新 更多