Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 810
Robin G Avatar asked Oct 24 '25 05:10

Robin G


2 Answers

Also, you can use it as a property value like this. (I used colors to visualize it)

const {
  createApp
} = Vue

const App = {
  methods: {
    textposit(pos) {
      if (pos == "left") {
        return "red"
      } else {
        return "blue"
      }
    }
  }
}

Vue.createApp(App).mount('#app')
<script src="https://unpkg.com/vue@next"></script>

<div id="app">
  <div :style="{color: textposit('left')}">TEXT</div>
  <div :style="{color: textposit('somethingelse')}">TEXT</div>
</div>
like image 115
doğukan Avatar answered Oct 25 '25 18:10

doğukan


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.

like image 27
Boussadjra Brahim Avatar answered Oct 25 '25 17:10

Boussadjra Brahim