SoFunction
Updated on 2025-04-11

Summary of several common methods of Vue dynamic style

Vue provides a variety of methods to set styles dynamically, and the following are several commonly used methods:

1. Object syntax:

You can dynamically style an object by binding an object in the template, where the key of the object is the CSS attribute name and the value is the corresponding value. The sample code is as follows:

<template>
  <div :style="{ color: textColor, fontSize: fontSize + 'px' }">Hello, world!</div>
</template>
<script>
export default {
  data() {
    return {
      textColor: 'red',
      fontSize: 16
    }
  }
}
</script>

2. Array Syntax

You can dynamically style it by binding an array in the template, where the elements in the array are objects, the key of the object is the CSS attribute name, and the value is the corresponding value. The sample code is as follows:

<template>
  <div :style="[baseStyles, activeStyles]">Hello, world!</div>
</template>
<script>
export default {
  data() {
    return {
      baseStyles: {
        color: 'red',
        fontSize: '16px'
      },
      activeStyles: {
        fontWeight: 'bold'
      }
    }
  }
}
</script>

3. Calculate properties

You can set the style dynamically by defining a computed property. The sample code is as follows:

<template>
  <div :style="styles">Hello, world!</div>
</template>
<script>
export default {
  data() {
    return {
      textColor: 'red',
      fontSize: 16
    }
  },
  computed: {
    styles() {
      return {
        color: ,
        fontSize:  + 'px'
      }
    }
  }
}
</script>

4. Object binding

You can set styles dynamically by defining a style object and binding the object in the template. The sample code is as follows:

<template>
  <div v-bind:style="styleObject">Hello, world!</div>
</template>
<script>
export default {
  data() {
    return {
      styleObject: {
        color: 'red',
        fontSize: '16px'
      }
    }
  }
}
</script>

The above is the commonly used method of dynamically setting styles in Vue, and just select the appropriate method according to the actual situation.

Summarize

This is the end of this article about several commonly used methods of Vue dynamic style. For more related content on Vue dynamic style, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!