I. Brief introduction

In the use of VUE development, often encapsulate a lot of components to facilitate reuse, so it is inevitable to write style related components, such as color, height and other style parameters when need to use. So the question is: how do we use the parameters received in the component in the style? In other words, how do we use variables in data in styles?

Second, code demonstration

This is really simple, there is no other knowledge, directly on the code:

<template>
  <div class="box" :style="styleVar">
  </div>
</template>
<script>
export default {
  props: {
    height: {
      type: Number.default: 54,}},computed: {
    styleVar() {
      return {
        '--box-height': this.height + 'px'}}}},</script>
<style scoped>
.box {
  height: var(--box-height);
}
</style>
Copy the code

In vue we have implemented the method of using JS variables in styles: and using CSS to define variables, inject variables in the line, and then use var() in style to get the data we set in the line.

Three, the last

In the future, it will be much easier to encapsulate UI components that require style parameters to be passed dynamically. Have you learned? Try it out in the project