Categories
Vue Answers

How to use props in CSS with In Vue.js?

Spread the love

Sometimes, we want to use props in CSS with In Vue.js.

In this article, we’ll look at how to use props in CSS with In Vue.js.

How to use props in CSS with In Vue.js?

To use props in CSS with In Vue.js, we can set the style prop to an object with prop values as CSS style values.

For instance, we write

<template>
  <div :style="style" @mouseover="mouseOver()"></div>
</template>

<script>
export default {
  props: ["color"],
  computed: {
    style() {
      return { "background-color": this.hovering ? this.color : "red" };
    },
  },
  data() {
    return {
      hovering: false,
    };
  },
  methods: {
    mouseOver() {
      this.hovering = !this.hovering;
    },
  },
};
</script>

to create the style computed property to return an object with background-color set to the this.color prop value if this.hovering is true.

Otherwise, we set it to 'red'.

And then we set the style prop to style to apply the styles with

:style="style"

We register the color prop

props: ["color"]

Conclusion

To use props in CSS with In Vue.js, we can set the style prop to an object with prop values as CSS style values.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *