Search code examples
javascriptcssvue.jsvuex

Can I use the return of a function to define the style of a div in vue?


Hey I want to call in the v-bind:style of my div the function textposit which uses the prop textpos as a parameter. The return of the function should change the style of the div depending on the parameters value.

<div class="container"  :style=" textposit(textpos) ">
       <p class="headline">{{ headline }}</p>
       <p class="text">{{ text }}</p>
</div>

This is my script:

export default {
    name: 'page',
    components: {
    },
    props:{
        headline: {
            type: String,
        },
        text: {
            type: String,
        },
        img: {
            type: String,
        },
        align:{
            type: String,
            default: "center",
        },
        textpos:{
            type: String,
            default: "left",
        },
        textrows:{
            type: Number,
            default: 1,
        }
    },
    methods:{
      textposit (pos){
            if (pos == "left") {
                return{
                    "grid-column: 4 / 5"
                }
            }
            else{
                 return{
                    "grid-column: 1 / 2"
                }
            }
        }
    }
}

It seems to call the method but does not change the style of my div. hope someone can help :) thank u


Solution

  • You could define it as computed property instead of method :

    <div class="container"  :style=" textposit">
    

    script :

    
    export default {
        name: 'page',
        components: {
        },
        props:{
           //....
        },
        computed:{
          textposit (){
                if (this.textpos === "left") {
                    return{
                        "grid-column": "4 / 5" 
                    }
                }
                else{
                     return{
                        "grid-column": "1 / 2"
                    }
                }
            }
        }
    }
    

    also I changed "grid-column: 4 / 5" to "grid-column": "4 / 5" to make it a valid object field.