Tengo un botón que ejecuta la función startProcess que generará un número aleatorio. Este número aleatorio se pasará como accesorio a Child.vue que se usará con estilo. Busqué en algunas páginas "Cómo usar accesorios con estilo en vue". La solución fue usar computed , pero nada parece funcionar. Para una mejor comprensión, por favor revise el código.
PS Este es un código simplificado. template, script, style eliminados.
aplicación.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(); }; }niño.vue
<button @click="logTop">Log</button> props: { top: Number }, computed: { return { cssProps() { "--top": `${this.top}%`; }; }; }; .foo { top: var(--top); };intente como el siguiente fragmento:
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>