备案名称和网站名称株洲发布最新通告
想要渲染一个元素的attribute,应该使用v-bind指令
- 由于插值表达式不能直接放在标签的属性中,所有要渲染元素的属性就应该使用v-bind
- v-bind可以用于渲染任何元素的属性,语法为 v-bind:属性名='数据名',可以简写为 :属性名='数据名'
<script setup>import {ref} from "vue";let str = "hello 2024";let myType=ref("checkbox")const data={name: "坚持",url: "https://blog.csdn.net/m0_65152767?type=blog",logo: "https://inscode.csdn.net/@m0_65152767",}</script><template><div><!--3.v-bind属性渲染、属性绑定--><!--v-bind:value可以简写成:value--><input type="text" v-bind:value="str"/><br><input type="text" :value="str"><br><input type="text" v-model="myType"><br><input :type="myType"><br><a v-bind:href="data.url" target="_self"><img :src="data.logo" :title="data.name"><br><imput type="button" :value="`点击访问${data.name}`"></imput></a></div></template>
在Vue3中,v-bind指令用于绑定属性或以动态的方式设置HTML属性。它的一般语法如下:
<div v-bind:属性名="属性值"></div>
也可以简写为:
<div :属性名="属性值"></div>
其中,属性名可以是任何HTML标签支持的属性,属性值可以是一个Vue表达式,例如:
<div :class="{ active: isActive, 'text-danger': hasError }"></div>
上面代码中,我们动态地设置了
class
属性,属性值是一个对象,根据isActive
和hasError
的值来设置active
和text-danger
类的存在与否。当且仅当isActive
为true
、hasError
为false
时,该元素会有active
类,text-danger
类则会被移除。除了对象语法,我们还可以使用数组语法,来动态地绑定多个类名:
<div :class="[activeClass, errorClass]"></div>
上面代码中,我们使用了数组语法,将
activeClass
和errorClass
两个变量的值作为class
属性值,这样就可以根据变量值的不同,动态地设置元素的类名了。