2

I have Vue.js application and there is a component with the code as following:

1) In "template" section:

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

2) In "data" section:

className: '',

3) In "methods" section:

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

4) In "style" section:

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

The panel's title uses first class in "style" section, which means the color of panel's title is black. When I click "save" button I call toggleColor method and under some condition I want to change the color to red. It doesn't work in this way. How to make it work?

2 Answers 2

1

You can set className by using :class="{'your-class-name': isAllowed}" pattern.

<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;
  }
},
Sign up to request clarification or add additional context in comments.

Comments

1

Presumably your title has its own element inside the panel component. You won't be able to add a CSS class directly to that element from outside the panel, you can only add classes to the panel's outer element. To add a class to the inner element you would expose a suitable prop on the panel and let the panel handle the styling.

However, to get it working using something similar to the code you had in the question you'd need to change this:

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

Trying to set the class to a selector is meaningless. Instead it should be:

this.className = 'panel-title-red'

That will put the class panel-title-red on the outermost element of the panel. That might not be the element you wanted but it's the best we can do from outside the panel. You'd then need suitable CSS to get that to take effect:

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

I'm assuming that will be going through a pre-processor as it isn't actually valid CSS but it is consistent with the code you posted.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.