Vue3动态改变css样式的方法,确实很简单很好用

直接在setup函数里面使用样式变量,就可以直接绑定到style样式标签中,而且可以动态修改切换,样例代码:

<template>
  <div class="box">
    <div>
      你好,世界
      <button @click="switchColor">切换字体颜色</button>
      <button @click="switchBorder">切换边框颜色</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'

// 动态样式
const style = ref('red')

const switchColor = () => {
  style.value = 'orange'
}

const border = reactive({
  border: '2px solid black'
})

const switchBorder = () => {
  border.border = '5px solid red'
}
</script>

<style scoped>
.box {
  width: 200px;
  height: 200px;
  color: v-bind(style);
  border: v-bind('border.border');
  padding: 10px;
}
</style>

结果样式展示: 

点击按钮就可以切换样式:

 

猜你喜欢

转载自blog.csdn.net/weixin_44786530/article/details/130862355