指令
指令 (Directives) 是带有 v- 前缀的特殊 attribute。Vue中所有带有v-开头的都是Vue的内置指令。
常用指令
v-text 用于显示文本
v-html 用于展示文本 <fontstyle=“color:#DD5145”>不建议使用
v-show 用于控制元素的显示与隐藏(相当于为元素添加 display:none; 样式)
v-if 用于控制元素的显示与隐藏(动态的向DOM树内添加或者删除DOM元素)
v-else if 表示v-if为false执行的指令,可以链式调用
v-on 可简写为 @ ,用来给元素绑定事件
v-bind 可简写为 : 用来绑定元素的属性Attr
v-model 主要用于表单的双向绑定
v-for 用来遍历元素
示例:
v-show:
<script setup lang="ts">
import { ref } from 'vue';
let whether = ref<boolean>(true)
const getWherther = ()=>{
whether.value = !whether.value
}
</script>
<template>
<button @click="getWherther">点击 显示/隐藏 文本内容</button>
<div v-show="whether">
<h2>嘿嘿哈哈嘿嘿</h2>
</div>
</template>
V-if /v-else if / v-else
<script setup lang="ts">
import { ref } from 'vue';
let whether = ref<boolean>(true)
const getWherther = () => {
whether.value = !whether.value
}
</script>
<template>
<div>
<button @click="getWherther">点击 显示/隐藏 文本内容</button>
<div v-if="whether">
<h2>嘿嘿哈哈嘿嘿</h2>
</div>
<div v-else="!whether">
<h2>笑不出来了</h2>
</div>
</div>
</template>
注: v-show 与 v-if 都用于控制元素的显示与隐藏,区别在于:v-show 操作样式,v-if 操作 DOM ;若频繁切换建议使用 v-show
v-on
<script setup lang="ts">
import { ref } from 'vue';
let whether = ref<boolean>(true)
const getWherther = () => {
whether.value = !whether.value
}
</script>
<template>
<div>
<h3 @click="getWherther">{{whether}}</h3>
</div>
</template>
v-bind
在这里插入代码片
```<script setup lang="ts">
import { ref } from 'vue';
let msg = ref<string>('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fdingyue.ws.126.net%2F2021%2F0514%2F1eb45120g00qt3hof0395d000cn00a0p.gif&refer=http%3A%2F%2Fdingyue.ws.126.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1651069469&t=ecce13acfde1884469164510ea8a12ff')
</script>
<template>
<div>
<img :src="msg" alt="图片">
</div>
</template>
## v-model
```javascript
在这里插入代码片
v-model
<script setup lang="ts">
import { reactive, ref } from 'vue';
let text= ref<string>('')
</script>
<template>
<div>
<input type="text" v-model="text">
</div>
</template>
v-for
<script setup lang="ts">
import { reactive, ref } from 'vue';
let masgs = reactive<string[]>([
'https://pic.rmb.bdstatic.com/0ce03a74dff864fcd80b4fac128aed168677.gif',
'https://img0.baidu.com/it/u=1177050093,2561561890&fm=253&fmt=auto&app=138&f=GIF?w=455&h=360',
'https://img0.baidu.com/it/u=2377911498,19241535&fm=253&fmt=auto&app=138&f=GIF?w=220&h=176'
])
</script>
<template>
<div class="image">
<div v-for="(item,index) in masgs" :key="index">
<img :src="item" alt="图片">
</div>
</div>
</template>
<style scoped lang="less">
.image{
display: flex;
justify-content: center;
img{
width: 200px;
height: 200px;
}
}
</style>