Vue3
一、props + emit
一、props + emit | 父子组件基础通信(最常用)
适用场景:父子组件一对一传值,父传子用 props,子通知父用 emit。 这是 Vue 最基础、最规范的通信方式。
- props:父组件 → 子组件
父组件传值:
<!-- 父组件 -->
<template>
<Child :msg="parentMsg" :info="userInfo" />
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const parentMsg = ref('来自父组件的数据')
const userInfo = ref({ name: '前端开发者' })
</script>
子组件接收, 中使用 defineProps:
<!-- 子组件 Child.vue -->
<script setup>
const props = defineProps({
msg: String,
info: {
type: Object,
required: true
}
})
// 只读!不建议直接修改 props
console.log(props.msg)
</script>
<template>
<div></div>
</template>
重要规则:props 是单向数据流,子组件不能直接修改 props。如果需要修改,要么通知父组件修改,要么用 computed /toRef 中转。
- emit:子组件 → 父组件,子向父发送事件
子组件触发事件:
<!-- 子组件 Child.vue -->
<script setup>
const emit = defineEmits(['change'])
const handleClick = () => {
emit('change', '子组件传给父的数据')
}
</script>
<template>
<button @click="handleClick">点我通知父组件</button>
</template>
父组件监听事件:
<!-- 父组件 -->
<Child @change="handleChange" />
<script setup>
const handleChange = (val) => {
console.log(val)
}
</script>
- 优点:简单清晰、单向数据流,便于排查;
- 缺点:只能父子之间使用,多层嵌套传值会出现「层层透传」,代码冗余。
二、defineModel
二、defineModel | 语法糖,替代 v-model 繁琐写法(Vue3.4 + 推荐)
以前Vue3实现v-model,
需要props:modelValue + emit(‘update:modelValue’),写法比较繁琐。
defineModel 是 Vue3.4 推出的语法糖,一行代码实现双向绑定,本质还是 props + emit 的封装。
子组件:
<!-- 子组件 Child.vue -->
<script setup>
const model = defineModel()
</script>
<template>
<input v-model="model" />
</template>
父组件直接使用 v-model:
<!-- 父组件 -->
<Child v-model="searchText" />
支持多个 v-model:
<!-- 子组件 -->
const name = defineModel('name')
const age = defineModel('age')
<!-- 父组件 -->
<Child v-model:name="form.name" v-model:age="form.age" />
- 优点:极简代码,专门用于双向绑定场景;
- 缺点:Vue3.4 以下版本不支持,底层依然是父子通信,不适合隔代。
- 提醒:不要滥用 defineModel,简单展示、单向传递的数据优先用 props。
三、defineExpose
三、defineExpose | 父组件拿到子组件实例、调用子组件方法 / 数据
默认情况下的组件内部属性和方法是封闭的,父组件通过 ref 获取子组件实例时,访问不到内部变量。 想要父调子,就用 defineExpose 暴露内容。
子组件:
<!-- 子组件 Child.vue -->
<script setup>
import { ref } from 'vue'
const childMsg = ref('子组件内部变量')
const childFn = () => {
alert('子组件方法被父调用')
}
// 对外暴露
defineExpose({
childMsg,
childFn
})
</script>
父组件:
<!-- 父组件 -->
<template>
<Child ref="childRef" />
</template>
<script setup>
import { ref, onMounted } from 'vue'
import Child from './Child.vue'
const childRef = ref(null)
onMounted(() => {
childRef.value.childFn()
console.log(childRef.value.childMsg)
})
</script>
适用场景:父组件需要主动调用子组件方法(弹窗打开、表单重置等); 缺点:属于命令式写法,尽量少用,优先用事件驱动。
四、provide /inject
四、provide /inject | 跨层级、隔代组件传值
如果组件层级很深:父 → 子 → 孙,一层层 props 传递非常麻烦,这时用 provide 和 inject。 祖先组件 provide 提供数据,任意后代组件 inject 注入,不受层级限制。
祖先组件:
<!-- 祖先组件 -->
<script setup>
import { ref, provide } from 'vue'
const theme = ref('dark')
provide('theme', theme)
</script>
任意后代组件(孙子、重孙都可以):
<!-- 任意后代组件 -->
<script setup>
import { inject } from 'vue'
const theme = inject('theme')
console.log(theme.value)
</script>
如果希望注入的值是响应式,一定要传 ref /reactive 响应式对象。
- 优点:跳过中间层级,适合全局主题、用户信息、配置项;
- 缺点:依赖关系不直观,数据来源不好追踪;不适合频繁修改、复杂状态。
最佳实践:provide 适合静态配置、全局上下文;频繁变更的共享数据优先 Pinia。
五、一张总表对比
五、一张总表对比,快速选择
| 通信方式 | 流向 | 适用场景 | 特点 |
|---|---|---|---|
| props + emit | 父 ↔ 子 | 普通父子传值、单向数据流 | 规范、最常用,多层嵌套透传麻烦 |
| defineModel | 父 ↔ 子 | 双向绑定(表单类组件) | props+emit 语法糖,简洁,Vue3.4+ |
| defineExpose + ref | 父 → 子 | 父调用子组件方法、获取子内部数据 | 命令式,慎用 |
| provide / inject | 祖先 → 任意后代 | 跨多层组件、全局配置 | 跳过中间组件,溯源困难 |
| Pinia | 任意组件 | 全局共享状态 | 大型项目复杂状态管理 |
六、选型口诀,方便记忆
- 普通父子单向传值:优先 props + emit
- 封装表单类组件,需要双向绑定:用 defineModel
- 父需要调用子弹窗、重置表单:用 defineExpose
- 多层嵌套、全局配置、主题:provide/inject
- 多个无关组件共享复杂状态:Pinia
七、高频坑点
- props 禁止直接修改,容易破坏单向数据流;
- defineModel 本质不是魔法,底层依然是 props 和 update 事件;
- provide 传普通字符串 / 数字,不是响应式,必须传 ref/reactive;
- defineExpose 只暴露你主动导出的变量,script setup 默认全部隐藏;
- provide/inject 不要用来做业务高频变更的数据,不好维护。
总结
组件通信没有绝对最好的方案,只有最合适的。
简单父子通信守住 props+emit 这个基础;双向绑定交给 defineModel;父需要主动操作子组件用 defineExpose;
跨层级静态上下文用 provide/inject。
理清边界,项目里就不会随意混用、代码越写越乱。
Pinia 替代 Vuex
Vue 官方已经把 Pinia 定为新一代状态管理方案,Vuex 不再维护。它去掉了繁琐的 mutations,API 简洁、天然适配 <script setup>、TS 类型友好,是现在 Vue3 项目的首选。
一、Pinia 和 Vuex 核心区别,先搞懂为什么换
Vuex 有三板斧:state、mutations、actions,还有 getters。强制要求同步修改走 mutations,写起来模板代码很多;嵌套 module、命名空间很容易写乱,TS 类型推导体验差。
Pinia 直接砍掉了 mutations,修改状态可以直接改,也可以统一放到 actions;没有嵌套模块,每一个 store 都是独立文件,天然隔离;完美适配组合式 API,TS 自动推导,devtools 调试友好,SSR 支持更好Pinia。
| 对比项 | Vuex | Pinia |
|---|---|---|
| 核心组成 | state / mutations / actions / getters | state /actions/getters(无 mutations) |
| 修改 state | 必须通过 mutations 同步 | 可直接修改,actions 支持同步 + 异步 |
| 模块 | 单根 store + 嵌套 module + 命名空间 | 多个独立 store,互相 import 直接调用 |
| TS 支持 | 需要额外类型封装,体验一般 | 原生友好,自动推断类型 |
| 写法风格 | 选项式为主 | 选项式 + Setup 组合式两种写法 |
| 官方状态 | 停止维护 | Vue 官方推荐 |
一句话总结:Pinia = Vuex5 的设计思路,更轻、更少约束、更贴合 Vue3。
二、安装 & 全局注册
#npm
npm install pinia
# pnpm
pnpm add pinia
在 main.js 注册 Pinia:
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app')
注册之后,整个项目都可以使用 store。
目录规范推荐:在 src 下新建 stores 文件夹,一个业务一个 store,比如 user.js、cart.js,不再像 Vuex 全部塞在 index.js。
三、定义一个 Store(两种写法)
defineStore 用来定义仓库,第一个参数是唯一 ID,devtools 靠这个区分仓库;第二个参数支持选项式写法和Setup 组合式写法。
写法 1:选项式(和 Vuex 思路接近,新手友好)
stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
// state:返回函数,避免多个实例共享状态,SSR必须函数形式
state: () => ({
count: 0,
name: 'Pinia测试'
}),
// getters:计算属性,缓存,和computed一样
getters: {
doubleCount: (state) => state.count * 2
},
// actions:同步、异步方法,替代Vuex的mutations+actions
actions: {
increment() {
// 直接this访问state
this.count++
},
async fetchNum() {
// 异步请求直接写,不需要区分mutation
const res = await new Promise(resolve => setTimeout(() => resolve(10), 500))
this.count = res
}
}
})
写法 2:Setup 写法(组合式风格,推荐<script setup项目)
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('counter', () => {
// state 用ref定义
const count = ref(0)
const name = ref('Pinia测试')
// getters 用computed
const doubleCount = computed(() => count.value * 2)
// actions 普通函数
function increment() {
count.value++
}
async function fetchNum() {
const res = await new Promise(resolve => setTimeout(() => resolve(10), 500))
count.value = res
}
return { count, name, doubleCount, increment, fetchNum }
})
两种写法功能完全一致,看团队习惯。Setup 写法更贴近 Vue3 组合式。
四、组件中使用 Store
<script setup>
import { useCounterStore } from '@/stores/counter'
// 获取store实例
const counterStore = useCounterStore()
</script>
<template>
<div>
<p>count:</p>
<p>两倍:</p>
<button @click="counterStore.increment">+1</button>
<button @click="counterStore.fetchNum">异步赋值</button>
</div>
</template>
直接解构会失去响应式:
// count不再响应
const { count } = useCounterStore()
需要解构又要保留响应式,使用 storeToRefs:
import { storeToRefs } from 'pinia'
const counterStore = useCounterStore()
// state、getters用storeToRefs
const { count, doubleCount } = storeToRefs(counterStore)
// actions直接解构,不需要storeToRefs
const { increment, fetchNum } = counterStore
五、state 常用操作
state 常用操作:直接修改、批量修改、重置
Pinia 允许直接修改 state,不需要像 Vuex 一样必须走 mutation:
const counterStore = useCounterStore()
// 直接改单个字段
counterStore.count = 99
// $patch 批量修改(推荐,减少多次触发devtools记录)
counterStore.$patch({
count: 10,
name: '新名字'
})
// $reset() 重置state回到初始值(选项式store支持,setup写法不自带)
counterStore.$reset()
六、Getters
和 computed 特性一致,有缓存,依赖不变不会重复执行。 getters 内部也可以访问其他 getter:
getters: {
doubleCount: (state) => state.count * 2,
tripleCount(state) {
return this.doubleCount + state.count
}
}
七、Actions:同步 + 异步统一写
这是 Pinia 最大的简化点,不再区分同步 mutation 和异步 action。所有逻辑都放在 actions,接口请求、业务逻辑统一封装。
actions: {
async login(account) {
const data = await api.login(account)
this.token = data.token
this.userInfo = data
}
}
组件直接调用:
userStore.login({name:'xxx'})
八、Store 之间互相调用(跨仓库取值)
Vuex 跨模块需要 rootState,Pinia 简单很多:直接 import 另一个 store 使用即可。 举个例子:在 userStore 里面读取 counterStore
import { defineStore } from 'pinia'
import { useCounterStore } from './counter'
export const useUserStore = defineStore('user', {
state: () => ({
userId: 1
}),
actions: {
logCount() {
const counter = useCounterStore()
console.log('来自counter的count', counter.count)
}
}
})
注意:只能在 store 的 action /getter 里面调用别的 store,不要在顶层直接调用。
九、实战必备:持久化存储(页面刷新不丢失)
开发登录态、用户信息,最常用需求:刷新页面 state 不丢失。推荐插件 pinia-plugin-persistedstate。
- 安装
pnpm add pinia-plugin-persistedstate
- main.js 注册插件
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
- store 开启持久化
export const useUserStore = defineStore('user', {
state: () => ({ token: '', userInfo: {} }),
// 开启持久化,默认全部state存入localStorage
persist: true
})
进阶配置:只持久化部分字段、切换 sessionStorage
persist: {
storage: sessionStorage,
paths: ['token'] // 只保存token,userInfo不持久化
}
十、Vuex 迁移小提示
- 每一个 Vuex module,拆成一个独立 Pinia store
- mutations 里面的逻辑全部迁移到 actions
- 写法不同:
this.$store.commit → store.xxx(); this.$store.dispatch → store.xxx() - 命名空间不再需要,直接导入对应 store
参考
Vue3 组件通信全梳理,props /emit/defineModel /provide/defineExpose 对比讲解 https://mp.weixin.qq.com/s/ctpOZnjRDX8yaapLQW1uOA
Pinia 完整入门教程,替代 Vuex,状态管理一次吃透 https://mp.weixin.qq.com/s/gqiAmRXtNSUhom-yJgrVTQ