v-bind 强制绑定解析表达式, 可以简写v-bind用:冒号

293 阅读1分钟

v-bind 指令用于将一个表达式的值动态地绑定到目标元素的属性上。通过 v-bind,我们可以实现将 Vue 实例的数据或表达式的值绑定到 HTML 属性的功能。v-bind 可以绑定的属性包括但不限于:

  1. HTML 属性:可以绑定常用的 HTML 属性,例如 idclassstylesrchref 等等。
  2. Vue 特殊属性:可以绑定 Vue 特定的属性,例如 v-bind:keyv-bind:isv-bind:ref 等等。

需要注意的是,v-bind 可以动态地绑定任何 JavaScript 表达式的值,这意味着你可以使用计算属性、方法、属性等来生成绑定的值。

v-bind 的常见用法是简写形式 :,例如 :class="className"。这样可以更加简洁地绑定属性,并提高代码的可读性。

<template>
  <div style="font-size: 14px">
    <!--原生写法只能使用字符串-->
    <a href="http://www.baidu.com">原生访问指定站点</a><br>
    <!--v-bind写法 能使用变量-->
    <a v-bind:href="url">v-bind访问指定站点2</a><br>
    <!--v-bind简写-->
    <a :href="url">简写:访问指定站点3</a><br>

    <!--v-bind简写 绑定 `id`、`class`、`style`、`src` -->
    <img :id="dateId"
    :class="imgClass" 
    :style="imgStyle" 
    :src="imgSrc">
  </div>
</template>

<script lang="ts">
// vue3.0版本语法
import { defineComponent, ref } from "vue";
export default defineComponent({
  name: "组件名",
  setup() {
    const url = ref('http://www.baidu.com');
    const imgSrc = ref(`https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png`)
    const imgClass = ref('bg-color-blue');
    const imgStyle = ref('width: 100px; height: 100px;');
    const dateId = ref(new Date().getTime() + '');

    return {
      url,dateId,imgClass,imgStyle,imgSrc
    };
  },
});
</script>

<style>
.bg-color-blue {
  background-color: blue;
}
</style>

页面显示效果:

image.png

在vue3.2版本之后v-bind还可以用在css里

<template>
  <div style="font-size: 14px">
    <!--vue3.2版本 支持的一种css里的 v-bind写法-->
    <div class="bg-color-blue">测试在css中使用v-bind的</div>
  </div>
</template>

<script lang="ts" setup>
// vue3.2版本语法
import { ref } from "vue";
const colorBlue = ref("blue");
const colorFff = ref("#fff");
</script>

<style>
.bg-color-blue {
  /*使用v-bind绑定js里的变量*/
  color: v-bind('colorFff');
  background: v-bind('colorBlue');
}
</style>

页面显示效果:

image.png