Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda