Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
Passing props that will be used in style in child component - Vue

I have a button that runs the function startProcess which will generate a random number. This random number will be passed as a prop to Child.vue that will be used in style. I looked into some pages How to use props in style in vue. The solution was to use computed, but nothing seems to work. For a better understanding, please check the code.

P.S. This is a simplified code. Removed template, script, style.

App.vue

<button @click="startProcess">Start</button>
<Child v-if="toggleChild" :top="top" />

data() {
    return {
        toggleChild: false,
        top: 0
    }
},
methods: {
    startProcess() {
        this.toggleChild = !this.toggleChild;
        this.top = Math.random();
    };
}

Child.vue

<button @click="logTop">Log</button>

props: { top: Number },
computed: {
    return {
        cssProps() {
            "--top": `${this.top}%`;
        };
    };
};

.foo {
  top: var(--top);
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

try like following snippet:

Vue.component('Child', {
  template: `
    <div class="">
      <button @click="logTop" class="foo" :style="cssProps">Log</button>
    </div>
  `,
  props: { top: Number, col: String },
  methods: {
    logTop() {
      console.log(this.top)
    }
  },
  computed: {
    cssProps() {
      return {
        '--top': `${this.top}%`,
        '--col': this.col
      }
    }
  }
})

new Vue({
  el: '#demo',
  data() {
    return {
      toggleChild: false,
      top: 0,
      col: ''
    }
  },
  methods: {
    startProcess() {
      this.toggleChild = !this.toggleChild;
      this.top = Math.random()*100;
      this.col = 'red'
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
.foo {
  position: absolute;
  top: var(--top);
  background-color: var(--col);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <button @click="startProcess">Start</button>
  <Child v-if="toggleChild" :top="top" :col="col" />
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!