学习优先度:★★★★☆

难易度:★★★★☆

Vue 的 v-bind 可用于根据 JavaScript 表达式将内联样式动态绑定到元素上。

v-bind 允许在 Vue.js 中动态绑定内联样式,使您可以有条件地应用样式。

【代码示例】

<div id="app">
  <div :style="{ color: activeColor, fontSize: fontSize + 'px' }">
  This div's inline styles are bound dynamically
 </div>
 <button @click="changeColor">Change Color</button>
 <button @click="increaseFontSize">Increase Font Size</button>
</div>
<script>
 new Vue({
  el: '#app',
  data: {
   activeColor: 'red',
   fontSize: 14
  },
  methods: {
   changeColor() {
​    this.activeColor = this.activeColor === 'red' ? 'blue' : 'red';
   },
   increaseFontSize() {
​    this.fontSize += 2;
   }
  }
 });
</script>

【执行结果】

A div that dynamically changes its inline styles based on the activeColor and fontSize data properties. Buttons alter these properties.

:style是v-bind:style的缩写。内联样式绑定允许动态应用CSS属性。activeColor和fontSize分别控制行内颜色和字体大小的样式。单击按钮会改变activeColor并增大fontSize,展示了动态样式绑定。这个特性可以根据应用程序状态动态改变元素的外观,增强用户交互和体验。

【补充】

Vue.js 支持多种样式绑定方式,包括对象和数组语法。内联样式绑定可用于依赖于反应数据属性的复杂样式操作,提供对元素外观的细粒度控制。