关于vue中v-bind的使用

在vue中,v-bind的常规用法是:用于在template中单向的绑定某些属性,使这些属性可以根据js中的响应式变量动态的更新。如

<template>
  <input v-bind:placeholder="text" type="text">
</template>

<script setup>
  import {ref} from 'vue'
  const text = ref('测试文字')
</script>

也许我们更熟悉的是它的简写方式,也就是省略v-bind,只用<input :placeholder="text" type="text">


但在今天研究动态变换css样式的时候,发现了v-bind的一个之前没注意到的用法:
v-bind除了在template中使用外,它还可以在style中使用,用与将css样式中的某个属性与js的变量关联起来,实现样式的响应式变化

<template>
  <div class="div"></div>
</template>
  
<script setup>
  import {reactive, ref} from 'vue'
  
   const color = ref('red')
</script>

<style scoped>
.div {
  width: 200px;
  height: 200px;
  background-color: v-bind('color');
}
</style>

其用法与在template中类似,但在v-bind的()中需要将变量加引号。并且在()中,也支持写入模板字符串"``"
在此基础上:

<template>
  <div class="div"></div>
  <button @click="click">点我</button>
</template>
  
<script setup>
  import {reactive, ref} from 'vue'
  
   const color = ref('red')
   function click() {
      color.value = color.value === 'red'? 'green': 'red'
   }
</script>

<style scoped>
.div {
  width: 200px;
  height: 200px;
  background-color: v-bind('color');
}
</style>

就实现了点击按钮对div背景颜色的切换。


参考: [https://juejin.cn/post/7005744294799605773]()
posted @ 2025-08-08 21:49  wenerda  阅读(4)  评论(0)    收藏  举报