How to add conditional styles in Vue.js using methods?
P粉327903045
P粉327903045 2024-03-21 20:53:17
0
1
448

I want to add a conditional style in a child component based on the prop value passed from the parent component.

This is a working example of conditional styling:

<li v-bind:class="[booleanValue ? 'stylingClassOne' : 'stylingClassTwo']"

But this only works when my style is based on a single variable and can only have two values ​​(true/false).

I want to implement conditional styling based on a variable that can take multiple values. Suppose I pass a string from parent component to child component stylingDecider, the value can be stylingClassOne, stylingClassTwo, stylingClassThree.

So I want to do the following: <li v-bind:class="getStylingClass(stylingDecider)"> But this does not work. The reason I need a method to decide what the style is is because there is some other processing going on that will return a class based on said processing, so I can't just use <li v-bind:class="stylingDecider " .

What did i do wrong? Please advise, thank you. I'm using Vue 3 and bootstrap-vue 3.

P粉327903045
P粉327903045

reply all(1)
P粉653045807

I just created a working code snippet:

Vue.component('child', {
  props: ['dynamicstyle'],
  template: `
  • Hello !!
`, methods: { getStylingClass(stylingDecider) { return stylingDecider; } } }); var app = new Vue({ el: '#app', data: { stylingDecider: 'stylingClassTwo' } });
.stylingClassTwo {
  background: green;
}
sssccc
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template