1、指令简介
Vue 指令(Directives)是 Vue.js 的一项核心功能,它们可以在 HTML 模板中以 v- 开头的特殊属性形式使用,用于将响应式数据绑定到 DOM 元素上或在 DOM 元素上进行一些操作。
Vue 指令是带有前缀 v- 的特殊 HTML 属性,它赋予 HTML 标签额外的功能
2、常用指令
3、v-bind示例
span添加一个tag的标签xiaobai
<script setup>
// v-bind 简写
let tag = "xiaobai"
</script>
<template>
<span :tag>小白</span>
</template>
<style scoped>
</style>
4、v-model示例
input 输入内容联动div 中的username变化
<script setup>
import {ref} from 'vue'
// v-model 双向绑定,
let username = ref("小白")
</script>
<template>
<input type ="text" v-model="username"></input>
<div>{{ username }}</div>
</template>
<style scoped>
</style>
5、v-if示例
页面没有生成小白1学vue的表情
<script setup>
let show = false
</script>
<template>
<div v-if="show">小白1学vue</div>
<div v-if="!show">小白2学vue</div>
</template>
<style scoped>
</style>
6、v-show示例
通过style="display: none;"隐藏标签内容
<script setup>
let show = false
</script>
<template>
<div v-show="show">小白1学vue</div>
<div v-show="!show">小白2学vue</div>
</template>
<style scoped>
</style>
7、v-for示例
循环生成,列表,表格等
<script setup>
let study = ["vue","javascript","typescript"]
let user = [
{'name':'小白','age':18},
{'name':'小花','age':19}
]
</script>
<template>
<ul>
<li v-for="(value,index) in study">{{ value }} - {{ index }}</li>
</ul>
<!--获取对象属性-->
<ul>
<li v-for="(value,key,index) in user[0]">{{ value }} - {{ index }} - {{key}}</li>
</ul>
<table>
<tr v-for="(item,index) in user">
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
</tr>
</table>
</template>
<style scoped>
tr, td, th {border: 1px solid #ccc;}
</style>
8、v-on 示例
绑定click事件
<script setup>
import {ref} from 'vue';
let count=ref(1);
let print = function(){
console.log('失去焦点')
}
</script>
<template>
<button v-on:click="count++">{{count}}</button>
<button @click="count++">{{count}}简写</button>
<input v-on:blur="print()"></input>
</template>
<style scoped>
button{
border: 1px red solid;
}
</style>