当前位置: 首页 > article >正文

​Vue3 常用指令、属性、方法速查表

以下是一份 Vue3 常用指令、属性、方法速查表,涵盖核心功能、Composition API 及实用技巧,方便快速查阅:

一、模板指令(Directives)

指令说明示例
v-bind / :动态绑定属性(支持简写 :<div :id="dynamicId">
v-model表单输入双向绑定(支持修饰符)<input v-model.trim="text">
v-on / @绑定事件(支持简写 @<button @click="handleClick">
v-for循环渲染元素(需加 key<li v-for="item in list" :key="item.id">
v-if / v-else条件渲染(动态添加/移除元素)<div v-if="show">显示内容</div>
v-show条件显示(通过 display 切换)<div v-show="isVisible">显示内容</div>
v-html渲染原始 HTML(注意 XSS 风险)<div v-html="rawHtml"></div>
v-slot定义插槽内容(可简写为 #<template #header>标题</template>
v-pre跳过编译(保留原始内容)<div v-pre>{{ 此处不编译 }}</div>
v-once只渲染一次(后续更新忽略)<div v-once>{{ staticContent }}</div>
v-memo缓存渲染结果(优化性能)<div v-memo="[value]">{{ value }}</div>

二、组件相关属性(Options & Props)

2.1 组件选项

属性说明示例
props定义组件接收的 props(支持类型校验)props: { title: String }
emits声明组件触发的事件(推荐显式定义)emits: ['update:modelValue']
setup()Composition API 入口(替代 data/methodssetup(props, { emit }) { ... }
computed计算属性(基于响应式依赖缓存)computed: { fullName() { ... } }
watch监听数据变化watch: { count(newVal) { ... } }

2.2 特殊属性

属性说明示例
ref注册模板引用(通过 ref 变量访问)<input ref="inputRef">const inputRef = ref(null)
key强制更新元素/组件(常用于 v-for<Component :key="id" />
is动态组件<component :is="currentComponent" />

三、Composition API 核心方法

方法说明示例
ref()创建响应式基本类型数据const count = ref(0)
reactive()创建响应式对象const state = reactive({ name: 'Alice' })
computed()创建计算属性const double = computed(() => count.value * 2)
watch()监听响应式数据变化watch(count, (newVal) => { ... })
watchEffect()自动追踪依赖的副作用函数watchEffect(() => console.log(count.value))
provide() / inject()跨组件传递数据(依赖注入)provide('key', value)const val = inject('key')
toRef() / toRefs()将响应式对象属性转为 refconst { name } = toRefs(state)

四、生命周期钩子

选项式 API

钩子触发时机
beforeCreate实例初始化前
created实例创建完成(数据已初始化)
beforeMount挂载到 DOM 前
mounted挂载完成(可访问 DOM)
beforeUpdate数据更新前(DOM 未重新渲染)
updated数据更新后(DOM 已重新渲染)
beforeUnmount实例销毁前
unmounted实例销毁完成

Composition API

钩子函数等价选项式钩子示例
onBeforeMountbeforeMountonBeforeMount(() => { ... })
onMountedmountedonMounted(() => { ... })
onBeforeUpdatebeforeUpdateonBeforeUpdate(() => { ... })
onUpdatedupdatedonUpdated(() => { ... })
onBeforeUnmountbeforeUnmountonBeforeUnmount(() => { ... })
onUnmountedunmountedonUnmounted(() => { ... })

五、路由与状态管理(Vue Router & Pinia)

Vue Router 常用方法

方法/属性说明示例
useRouter()获取路由实例const router = useRouter()
useRoute()获取当前路由信息const route = useRoute()
router.push()导航到新页面router.push('/home')
router.replace()替换当前页面(无历史记录)router.replace('/login')
router.go()前进/后退历史记录router.go(-1)

Pinia 核心 API

方法说明示例
defineStore()创建 Storeconst useStore = defineStore('id', { ... })
store.$patch()批量更新状态store.$patch({ count: 10 })
store.$reset()重置状态到初始值store.$reset()
store.$subscribe()监听状态变化store.$subscribe((mutation) => { ... })

六、实用代码片段

全局状态管理(Pinia)

// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  actions: {
    increment() { this.count++ }
  }
});

// 组件中使用
import { useCounterStore } from '@/stores/counter';
const counter = useCounterStore();
counter.increment();

表单验证(v-model + 修饰符)

<template>
  <input v-model.trim="username" @blur="validateUsername">
</template>

<script setup>
const username = ref('');
const validateUsername = () => {
  if (!username.value) alert('用户名不能为空');
};
</script>

API 请求封装

import { ref } from 'vue';
import axios from 'axios';

export function useFetch(url) {
  const data = ref(null);
  const error = ref(null);

  axios.get(url)
    .then(res => data.value = res.data)
    .catch(err => error.value = err);

  return { data, error };
}

七、注意事项

  1. 响应式数据:修改 ref 值需用 .valuereactive 对象可直接修改属性。
  2. 列表渲染:始终为 v-for 添加唯一的 key,避免渲染错误。
  3. 样式作用域:使用 <style scoped> 限制组件样式作用域。
  4. 性能优化:大列表使用 v-memo 或虚拟滚动(如 vue-virtual-scroller)。

资源推荐

  • Vue3 官方文档
  • Vue Router 文档
  • Pinia 文档

提示:善用 Vue Devtools 浏览器插件调试组件和状态! 🛠️

📚 推荐阅读

  • 无限畅用Cursor 编辑器,四步轻松搞定!
  • 历时两周半开发的一款加载live2模型的浏览器插件
  • github优秀开源作品集

http://www.kler.cn/a/564706.html

相关文章:

  • 【Oracle专栏】Oracle 之 回收站
  • 保护密码等敏感信息的几个常用方法
  • 如何制作安装包打包软件
  • 千峰React:Hooks(上)
  • 【Linux】线程详解
  • 文件操作 -- IO [Java EE 初阶]
  • LangChain教程 - RAG - PDF问答
  • (八)Java-Collection
  • (面试经典问题之无锁队列篇)无锁队列的基本原理及其作用
  • 【easy视频 | day01】项目了解 + 登录注册 + 使用 token 作为客户端请求令牌
  • 2.4 自动化评测答疑机器人的表现-大模型ACP模拟题-真题
  • 日志分析集群安装部署(ELK) 保姆级教程
  • LLVM - 编译器前端 - 将源文件转换为抽象语法树
  • 大中型虚拟化园区网络设计
  • IDEA入门及常用快捷键
  • 【02】Cocos游戏开发引擎从0开发一款游戏-cocos项目目录结构熟悉-调试运行项目-最重要的assets资源文件认识-场景sense了解-优雅草卓伊凡
  • 3DM转换成STL
  • 解决npm run dev报错
  • JavaScript 作用域与作用域链深度解析
  • 服务器为什么会禁止 Ping?服务器禁止 Ping 的好处