search

Home  >  Q&A  >  body text

How to add conditional styles in Vue.js using methods?

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粉327903045P粉327903045242 days ago423

reply all(1)I'll reply

  • P粉653045807

    P粉6530458072024-03-22 18:24:16

    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
    

    reply
    0
  • Cancelreply