Home > Software design >  Passing props that will be used in style in child component - Vue
Passing props that will be used in style in child component - Vue

Time:12-05

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);
};

CodePudding user response:

try like following snippet:

Vue.component('Child', {
  template: `
    <div >
      <button @click="logTop"  :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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related