Skip to content

指令大全

Vue的指令系统是Vue模板语法的重要组成部分,它允许你在模板中执行各种操作。本章节将详细介绍Vue3中的常用指令。

指令的基本概念

指令是带有 v- 前缀的特殊属性,用于在模板中执行各种操作。指令的语法为:

html
<element v-directive:argument.modifier="expression"></element>
  • directive:指令名称
  • argument:指令参数(可选)
  • modifier:指令修饰符(可选)
  • expression:指令表达式

常用指令

1. v-bind

作用:绑定HTML属性 简写:示例

vue
<template>
  <div>
    <img :src="imageUrl" :alt="imageAlt">
    <div :class="{ active: isActive }">Active</div>
    <div :style="{ color: textColor, fontSize: '16px' }">Styled text</div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const imageUrl = ref('https://example.com/image.jpg')
const imageAlt = ref('Example image')
const isActive = ref(true)
const textColor = ref('red')
</script>

2. v-model

作用:双向绑定 示例

vue
<template>
  <div>
    <input v-model="message" type="text">
    <p>{{ message }}</p>
    <input v-model.number="count" type="number">
    <p>{{ count }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const message = ref('')
const count = ref(0)
</script>

3. v-on

作用:绑定事件 简写@示例

vue
<template>
  <div>
    <button @click="increment">Increment</button>
    <p>{{ count }}</p>
    <button @click="sayHello('Vue3')">Say Hello</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const count = ref(0)

const increment = () => {
  count.value++
}

const sayHello = (name) => {
  alert(`Hello ${name}!`)
}
</script>

4. v-if / v-else / v-else-if

作用:条件渲染 示例

vue
<template>
  <div>
    <div v-if="score >= 90">优秀</div>
    <div v-else-if="score >= 80">良好</div>
    <div v-else-if="score >= 60">及格</div>
    <div v-else>不及格</div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const score = ref(85)
</script>

5. v-show

作用:显示/隐藏元素 示例

vue
<template>
  <div>
    <button @click="toggle">Toggle</button>
    <div v-show="isVisible">This is visible</div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const isVisible = ref(true)

const toggle = () => {
  isVisible.value = !isVisible.value
}
</script>

6. v-for

作用:列表渲染 示例

vue
<template>
  <div>
    <ul>
      <li v-for="(item, index) in items" :key="index">
        {{ item.name }} - {{ item.age }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const items = ref([
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Bob', age: 35 }
])
</script>

7. v-text

作用:设置元素的文本内容 示例

vue
<template>
  <div>
    <p v-text="message"></p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const message = ref('Hello Vue3!')
</script>

8. v-html

作用:设置元素的HTML内容 示例

vue
<template>
  <div>
    <div v-html="htmlContent"></div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const htmlContent = ref('<h1>Hello Vue3!</h1>')
</script>

9. v-pre

作用:跳过元素及其子元素的编译 示例

vue
<template>
  <div>
    <div v-pre>{{ message }}</div>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const message = ref('Hello Vue3!')
</script>

10. v-once

作用:只渲染元素一次 示例

vue
<template>
  <div>
    <div v-once>{{ message }}</div>
    <button @click="changeMessage">Change Message</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const message = ref('Hello Vue3!')

const changeMessage = () => {
  message.value = 'Hello World!'
}
</script>

11. v-cloak

作用:在Vue实例挂载前隐藏元素 示例

vue
<template>
  <div>
    <div v-cloak>{{ message }}</div>
  </div>
</template>

<style>
[v-cloak] {
  display: none;
}
</style>

<script setup>
import { ref } from 'vue'

const message = ref('Hello Vue3!')
</script>

指令修饰符

1. v-on 修饰符

stop:阻止事件冒泡

vue
<template>
  <div @click="parentClick">
    <button @click.stop="childClick">Click</button>
  </div>
</template>

<script setup>
const parentClick = () => {
  console.log('Parent clicked')
}

const childClick = () => {
  console.log('Child clicked')
}
</script>

prevent:阻止默认事件

vue
<template>
  <form @submit.prevent="onSubmit">
    <button type="submit">Submit</button>
  </form>
</template>

<script setup>
const onSubmit = () => {
  console.log('Form submitted')
}
</script>

capture:使用事件捕获模式

vue
<template>
  <div @click.capture="parentClick">
    <button @click="childClick">Click</button>
  </div>
</template>

<script setup>
const parentClick = () => {
  console.log('Parent clicked')
}

const childClick = () => {
  console.log('Child clicked')
}
</script>

self:只当事件在元素本身触发时才执行

vue
<template>
  <div @click.self="parentClick">
    <button @click="childClick">Click</button>
  </div>
</template>

<script setup>
const parentClick = () => {
  console.log('Parent clicked')
}

const childClick = () => {
  console.log('Child clicked')
}
</script>

once:事件只执行一次

vue
<template>
  <button @click.once="clickOnce">Click once</button>
</template>

<script setup>
const clickOnce = () => {
  console.log('Clicked once')
}
</script>

passive:告诉浏览器事件处理函数不会阻止默认行为

vue
<template>
  <div @scroll.passive="onScroll">Scroll</div>
</template>

<script setup>
const onScroll = () => {
  console.log('Scrolled')
}
</script>

2. v-model 修饰符

lazy:延迟更新,在失去焦点或按下回车键时更新

vue
<template>
  <div>
    <input v-model.lazy="message" type="text">
    <p>{{ message }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const message = ref('')
</script>

number:将输入值转换为数字

vue
<template>
  <div>
    <input v-model.number="count" type="number">
    <p>{{ typeof count }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const count = ref(0)
</script>

trim:去除输入值的首尾空格

vue
<template>
  <div>
    <input v-model.trim="name" type="text">
    <p>{{ name }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const name = ref('')
</script>

3. v-bind 修饰符

prop:将属性绑定为DOM property

vue
<template>
  <div>
    <my-component :foo.prop="value"></my-component>
  </div>
</template>

camel:将kebab-case属性转换为camelCase

vue
<template>
  <div>
    <my-component :my-prop.camel="value"></my-component>
  </div>
</template>

sync:双向绑定(Vue 2中使用,Vue 3中已废弃)

自定义指令

除了内置指令外,你还可以创建自定义指令。

1. 全局自定义指令

javascript
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})

app.mount('#app')

2. 局部自定义指令

vue
<template>
  <input v-focus type="text">
</template>

<script>
export default {
  directives: {
    focus: {
      mounted(el) {
        el.focus()
      }
    }
  }
}
</script>

3. 自定义指令的钩子函数

javascript
directive('directiveName', {
  // 在元素被挂载到DOM时调用
  mounted(el, binding, vnode) {},
  
  // 在元素被更新时调用
  updated(el, binding, vnode) {},
  
  // 在元素被卸载时调用
  unmounted(el, binding, vnode) {}
})

指令的最佳实践

1. 合理使用指令

  • v-if vs v-show:对于频繁切换的元素使用v-show,对于不频繁切换的元素使用v-if
  • v-for 的key:始终为v-for添加key属性,提高渲染性能
  • 避免在v-for中使用v-if:这会影响性能,应该在计算属性中过滤数据

2. 简化指令使用

  • 使用指令的简写形式,如 : 代替 v-bind:@ 代替 v-on:
  • 对于简单的表达式,直接在模板中使用;对于复杂的逻辑,使用计算属性或方法

3. 自定义指令的使用场景

  • 表单验证:创建自定义指令来验证表单输入
  • 滚动处理:创建自定义指令来处理滚动事件
  • 拖拽功能:创建自定义指令来实现拖拽功能
  • 权限控制:创建自定义指令来控制元素的显示/隐藏

总结

Vue的指令系统是Vue模板语法的重要组成部分,它允许你在模板中执行各种操作。通过内置指令,你可以实现数据绑定、事件处理、条件渲染、列表渲染等功能;通过自定义指令,你可以扩展Vue的功能,满足特定的业务需求。

在后续的章节中,我们将学习Vue3的计算属性和监听属性,以及它们的使用方法和最佳实践。

© 2026 编程马·菜鸟教程 版权所有