现在位置: 首页 > Vue3 教程 > 正文

Vue3 v-bind 指令

Vue3 内置指令 Vue3 内置指令


v-bind 指令用于动态绑定属性或组件 prop,使属性值可以响应数据变化。


基本说明

v-bind 指令用于动态地将一个或多个属性绑定到表达式。它允许属性的值是动态的,而不是固定的字符串。

  • 简写: : 或 .(prop 修饰符时)
  • 期望类型: any (带参数) | Object (不带参数)
  • 作用: 动态绑定属性或 prop。

基本用法

实例

<!-- 完整写法 -->
<img v-bind:src="imageSrc" />

<!-- 简写 -->
<img :src="imageSrc" />

实例

<template>
  <div>
    <img :src="currentImage" :alt="imageAlt" />
    <button @click="changeImage">切换图片</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentImage: '/images/photo1.jpg',
      imageAlt: '风景图'
    }
  },
  methods: {
    changeImage() {
      this.currentImage = this.currentImage === '/images/photo1.jpg'
        ? '/images/photo2.jpg'
        : '/images/photo1.jpg'
    }
  }
}
</script>

动态绑定 class 和 style

实例

<!-- 动态绑定 class -->
<div :class="{ active: isActive }">内容</div>

<!-- 动态绑定 style -->
<div :style="{ color: textColor, fontSize: fontSize + 'px' }">样式</div>

Vue3 内置指令 Vue3 内置指令