元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
Vue3 基础
▶
环境搭建
安装与配置
项目创建
开发工具
▶
模板语法
插值表达式
指令系统
事件处理
▶
核心概念
▶
响应式系统
ref与reactive
计算属性
侦听器
▶
组合式API
setup函数
生命周期钩子
自定义Hooks
▶
组件开发
▶
组件基础
组件通信
Props详解
插槽机制
▶
高级组件
动态组件
异步组件
递归组件
▶
状态管理
▶
Vuex基础
状态存储
模块化
组合式写法
▶
Pinia
创建Store
状态操作
插件机制
发布时间:
2025-03-22 12:09
↑
☰
# Vue3 指令系统详解 本文将详细介绍Vue3中的指令系统,包括内置指令和自定义指令的使用方法。 ## 内置指令 ### 1. v-bind 用于动态绑定属性: ```vue <template> <div> <!-- 基础用法 --> <img v-bind:src="imageUrl" /> <!-- 简写形式 --> <img :src="imageUrl" /> <!-- 动态属性名 --> <button :[buttonAttr]="buttonValue">Click me</button> <!-- 绑定对象 --> <div v-bind="objectOfAttrs"></div> </div> </template> <script setup> import { ref } from 'vue' const imageUrl = ref('/images/logo.png') const buttonAttr = ref('disabled') const buttonValue = ref(true) const objectOfAttrs = ref({ id: 'container', class: 'wrapper' }) </script> ``` ### 2. v-on 用于事件处理: ```vue <template> <div> <!-- 基础用法 --> <button v-on:click="handleClick">Click</button> <!-- 简写形式 --> <button @click="handleClick">Click</button> <!-- 内联处理器 --> <button @click="count++">Add 1</button> <!-- 修饰符 --> <form @submit.prevent="handleSubmit"> <button>Submit</button> </form> <!-- 键盘事件 --> <input @keyup.enter="handleEnter" /> </div> </template> <script setup> import { ref } from 'vue' const count = ref(0) const handleClick = () => { console.log('Button clicked') } const handleSubmit = () => { console.log('Form submitted') } const handleEnter = () => { console.log('Enter pressed') } </script> ``` ### 3. v-model 用于表单双向绑定: ```vue <template> <div> <!-- 文本输入 --> <input v-model="text" /> <p>Text: {{ text }}</p> <!-- 复选框 --> <input type="checkbox" v-model="checked" /> <p>Checked: {{ checked }}</p> <!-- 单选按钮 --> <input type="radio" v-model="picked" value="one" /> <input type="radio" v-model="picked" value="two" /> <p>Picked: {{ picked }}</p> <!-- 选择框 --> <select v-model="selected"> <option value="">Please select</option> <option value="a">A</option> <option value="b">B</option> </select> <p>Selected: {{ selected }}</p> </div> </template> <script setup> import { ref } from 'vue' const text = ref('') const checked = ref(false) const picked = ref('') const selected = ref('') </script> ``` ### 4. v-if/v-else/v-else-if 用于条件渲染: ```vue <template> <div> <h2 v-if="type === 'A'">Type A</h2> <h2 v-else-if="type === 'B'">Type B</h2> <h2 v-else>Other Type</h2> <!-- 使用template包裹多个元素 --> <template v-if="showGroup"> <h2>Title</h2> <p>Paragraph 1</p> <p>Paragraph 2</p> </template> </div> </template> <script setup> import { ref } from 'vue' const type = ref('A') const showGroup = ref(true) </script> ``` ### 5. v-show 用于切换元素的显示状态: ```vue <template> <div> <h2 v-show="visible">This may be visible or hidden</h2> </div> </template> <script setup> import { ref } from 'vue' const visible = ref(true) </script> ``` ### 6. v-for 用于列表渲染: ```vue <template> <div> <!-- 基础用法 --> <ul> <li v-for="item in items" :key="item.id"> {{ item.text }} </li> </ul> <!-- 带索引 --> <ul> <li v-for="(item, index) in items" :key="item.id"> {{ index }}. {{ item.text }} </li> </ul> <!-- 遍历对象 --> <ul> <li v-for="(value, key) in object" :key="key"> {{ key }}: {{ value }} </li> </ul> </div> </template> <script setup> import { ref } from 'vue' const items = ref([ { id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' }, { id: 3, text: 'Item 3' } ]) const object = ref({ name: 'John', age: 30, city: 'New York' }) </script> ``` ## 自定义指令 ### 1. 基础用法 ```vue <template> <div> <input v-focus /> </div> </template> <script setup> // 局部注册 const vFocus = { mounted: (el) => el.focus() } </script> ``` ### 2. 全局注册 ```javascript // main.js const app = createApp(App) app.directive('focus', { mounted: (el) => el.focus() }) ``` ### 3. 指令钩子函数 ```javascript app.directive('example', { // 在绑定元素的 attribute 前调用 created(el, binding, vnode, prevVnode) { // 做些初始化工作 }, // 在元素被插入到 DOM 前调用 beforeMount(el, binding, vnode, prevVnode) { // 设置初始状态 }, // 在绑定元素的父组件被挂载后调用 mounted(el, binding, vnode, prevVnode) { // 添加事件监听器等 }, // 在更新前调用 beforeUpdate(el, binding, vnode, prevVnode) { // 处理更新前的清理工作 }, // 在更新后调用 updated(el, binding, vnode, prevVnode) { // 处理更新后的操作 }, // 在卸载前调用 beforeUnmount(el, binding, vnode, prevVnode) { // 清理工作,比如移除事件监听器 }, // 在卸载后调用 unmounted(el, binding, vnode, prevVnode) { // 最终的清理工作 } }) ``` ### 4. 实用示例 #### 点击外部关闭指令 ```javascript app.directive('click-outside', { mounted(el, binding) { el._clickOutside = (event) => { if (!(el === event.target || el.contains(event.target))) { binding.value(event) } } document.addEventListener('click', el._clickOutside) }, unmounted(el) { document.removeEventListener('click', el._clickOutside) } }) ``` 使用示例: ```vue <template> <div v-click-outside="closeDropdown" class="dropdown"> <!-- 下拉菜单内容 --> </div> </template> <script setup> const closeDropdown = () => { // 处理关闭逻辑 } </script> ``` #### 延迟加载指令 ```javascript app.directive('lazy', { mounted(el, binding) { const observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { el.src = binding.value observer.unobserve(el) } }) }) observer.observe(el) } }) ``` 使用示例: ```vue <template> <img v-lazy="imageUrl" /> </template> <script setup> const imageUrl = ref('https://example.com/image.jpg') </script> ``` ## 最佳实践 ### 1. 指令命名 ```javascript // 推荐的命名方式 app.directive('my-directive', { /* ... */ }) // 在模板中使用 <div v-my-directive></div> ``` ### 2. 参数传递 ```vue <template> <div> <!-- 传递多个参数 --> <div v-tooltip="{ text: 'Tooltip text', position: 'top', delay: 200 }">Hover me</div> </div> </template> ``` ### 3. 动态指令参数 ```vue <template> <div> <button v-[direction]="handler">Click me</button> </div> </template> <script setup> import { ref } from 'vue' const direction = ref('click') const handler = () => { console.log('Button clicked') } </script> ``` ## 总结 本文详细介绍了Vue3指令系统的使用方法: 1. 内置指令 - v-bind:属性绑定 - v-on:事件处理 - v-model:双向绑定 - v-if/v-else/v-else-if:条件渲染 - v-show:显示切换 - v-for:列表渲染 2. 自定义指令 - 基础用法 - 全局注册 - 钩子函数 - 实用示例 3. 最佳实践 - 指令命名规范 - 参数传递方式 - 动态指令使用 通过合理使用Vue3的指令系统,可以大大提高开发效率和代码可维护性。建议在实际开发中根据具体需求选择合适的指令,并遵循最佳实践来编写高质量的代码。