How to use style dynamically in vue3

In Vue 3, you can use styles dynamically in the following ways:

  1. Object syntax: You can set styles dynamically by binding an object. Use the directive in a template :styleand pass an object as value, with the object's keys representing the style properties and the value representing the style's value. For example:
<template>
  <div :style="dynamicStyles"></div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      dynamicStyles: {
      
      
        color: 'red',
        fontSize: '16px'
      }
    };
  }
};
</script>

You can dynamicStylesdynamically set style properties in the object as needed.

  1. Array syntax: You can set styles dynamically by binding an array. Use the directive in a template :styleand pass an array as value, where each element in the array is a style object. Style objects can be computed properties, objects returned by methods, or dataobjects defined directly in . For example:
<template>
  <div :style="[dynamicStyles, additionalStyles]"></div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      dynamicStyles: {
      
      
        color: 'red',
        fontSize: '16px'
      }
    };
  },
  computed: {
      
      
    additionalStyles() {
      
      
      return {
      
      
        backgroundColor: 'blue',
        fontWeight: 'bold'
      };
    }
  }
};
</script>

In the above example, dynamicStylesand additionalStylesare both style objects, and they will be combined and applied to the element.

  1. Component methods: You can define a method in the component that returns a style object and call the method in the template. For example:
<template>
  <div :style="getDynamicStyles"></div>
</template>

<script>
export default {
      
      
  methods: {
      
      
    getDynamicStyles() {
      
      
      return {
      
      
        color: 'red',
        fontSize: '16px'
      };
    }
  }
};
</script>

In this way, getDynamicStylesthe method is called every time the component is re-rendered, thus dynamically generating the style object.

The above are several common ways to use styles dynamically. You can choose a suitable method to dynamically set styles according to your specific needs.

Guess you like

Origin blog.csdn.net/weixin_48998573/article/details/133216085