小纸条1号
小纸条1号
发布于 2025-09-03 / 1 阅读
0

vue3小白,基础2,指令学习

1、指令简介

Vue 指令(Directives)是 Vue.js 的一项核心功能,它们可以在 HTML 模板中以 v- 开头的特殊属性形式使用,用于将响应式数据绑定到 DOM 元素上或在 DOM 元素上进行一些操作。

Vue 指令是带有前缀 v- 的特殊 HTML 属性,它赋予 HTML 标签额外的功能

2、常用指令

指令

描述

v-bind

用于将 Vue 实例的数据绑定到 HTML 元素的属性上。

v-if

用于根据表达式的值来条件性地渲染元素或组件。

v-show

v-show 是 Vue.js 提供的一种指令,用于根据表达式的值来条件性地显示或隐藏元素。

v-for

用于根据数组或对象的属性值来循环渲染元素或组件。

v-on

用于在 HTML 元素上绑定事件监听器,使其能够触发 Vue 实例中的方法或函数。

v-model

用于在表单控件和 Vue 实例的数据之间创建双向数据绑定。

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>