讲一下,vue3中,v-bind指令的核心用法。
v-bind是vue3中的内置指令,而且也是最常用的指令。它的主要作用是对标签元素中的属性进行绑定。
1、基础用法
- 用v-bind,添加属性。
v-bind最基础的用法就是添加属性了。我们使用v-bind指令,就可以向img这个标签添加src属性。
下面这个代码案例,hehe0赋值为'/favicon.ico'。
<template>
<div>
<img v-bind:src="hehe0"> //v-bind的两种写法
<img :src="hehe0"> //也可以简写:把v-bind去掉,仅留下冒号
</div>
</template>
<script setup>
import { ref } from 'vue';
const hehe0 = ref('/favicon.ico')
</script>
<style scoped>
</style>
key值绑定。
例如,我们定义一个动态的属性叫做keyHeihei, 把它赋值为 alt。它对应的value值,赋值为vHeiHei。如下所示:
<template>
<div>
<img v-bind:src="hehe0" :[keyHeihei]="'vHeiHei'">//这里使用单引号,可以直接赋值一个字符串
</div>
</template>
<script setup>
import { ref } from 'vue';
const keyHeihei = ref('alt')
const hehe0 = ref('/favicon.ico')
</script>
<style scoped>
</style>
可以看到,浏览器渲染符合我们的预期。

- 仅使用一个冒号绑定。
这种写法,key保持不变,value会根据script中的赋值,而发生改变。
下面这个案例中的haha属性没什么含义,只是为了代码演示而已。展示如下:
<template>
<div>
<img :haha />
</div>
</template>
<script setup>
import { ref } from 'vue';
const haha = ref('/favicon.ico')
</script>
<style scoped>
</style>

2、绑定多个属性
v-bind一次性绑定多个属性
用花括号,一次性绑定多个属性。花括号里,key保持不变,value会根据脚本里的赋值语句,发生改变。
代码展示如下:
<template>
<div v-bind="{ id: someProp, jj: someProp }"></div>
</template>
<script setup>
const someProp = '123'
const jj = "hh"
</script>
<style scoped></style>

- 定义一个对象,进行绑定
可以在脚本里定义一个对象objectOfAttrs ,然后在标签中通过v-bind引用它。
这个对象里面,有多个属性,如下所示:
<template>
<div v-bind="objectOfAttrs">
</div>
</template>
<script setup>
const objectOfAttrs = { //不用ref也是可以的
haha: '123',
id: 'container',
class: 'wrapper',
style: 'width:100px;height:100px;background-color:green'
}
</script>
<style scoped></style>
从图中可以看到,属性已经成功渲染。

3、class属性绑定
class是元素的内置属性,可以用如下方法进行定义。
中括号很好理解,就是把赋值后的变量丢进去,作为class属性的value。
花括号略微复杂。花括号的key为class的value,而花括号里的value是一个布尔值。如果为true,则告诉浏览器:这个key要渲染出来。
这里会有点绕,大家看一下代码就能准确理解了。
代码展示如下:
<template>
<div :class="{ hehe: isHehe }"></div>
<div :class="[hehe, heihei]"></div>
<div :class="[hehe, { 444: isHehe }]"></div>
<div :class="[hehe, { 444: isTT }]"></div>
</template>
<script setup>
const hehe = "123"
const isHehe = true
const heihei = "456"
const isTT = false
</script>
<style scoped></style>
展示结果如下:

4、style属性绑定
style是标签元素的内置属性,主要用来定义元素的样式。
- 驼峰命名法
style属性的value值,在定义的时候,可以使用驼峰命名法。vue会识别出来,你要定义的样式。
代码如下所示,用驼峰法,定义了一个fontWeight样式。
vue在渲染的时候,把fontWeight识别为font-weight,并添加到了style里。其它的fontWeight123、fontweight这些样式,vue都无法成功识别。
<template>
<div :style="{ fontWeight: 'bold' }"></div>
<div :style="{ fontWeight123: 'bold' }"></div> //不会渲染
<div :style="{ fontweight: 'bold' }"></div> //不会渲染
</template>
<script setup>
const fontWeight123 = "hehe"
</script>
<style scoped></style>

- 变量方式添加
我们还可以通过声明一个变量,把它放进style。如下所示:
<template>
<div :style="[styleObjectA, styleObjectB]"></div>
<div :style="styleObjectA"></div>
</template>
<script setup>
const styleObjectA = { fontSize: '16px', color: 'black' }
const styleObjectB = { fontWeight: 'bold' }
</script>
<style scoped></style>

以上,就是关于v-bind最核心、最常用的用法,感谢阅读。

1330

被折叠的 条评论
为什么被折叠?



