Vue3祖先后代组件数据双向同步实现方法

在 Vue3 中实现祖先后代组件的双向数据同步,可以通过组合式 API 的 provide/inject 配合响应式数据实现。以下是两种常见实现方案:


方案一:共享响应式对象 + 方法

html






方案二:计算属性双向绑定

html









方案三:Vuex/Pinia 全局状态管理(适合复杂场景)

js

// store.js
import { defineStore } from 'pinia'

export useStore = defineStore('data', () => {
  const value = ref('初始值')
  return { value }
})






最佳实践建议:

  1. 简单场景使用 provide/inject + 响应式对象

  2. 中大型项目推荐使用 Pinia

  3. 需要严格数据流时,建议通过方法修改数据而非直接赋值

  4. 使用 TypeScript 时建议定义 InjectionKey 增强类型提示

ts

// 类型安全版本
import type { InjectionKey } from 'vue'

interface DataType {
  value: Ref
  update: (val: string) => void
}

const dataKey: InjectionKey = Symbol()

// 祖先组件
provide(dataKey, { value, updateValue })

// 后代组件
const { value, update } = inject(dataKey)! // 非空断言

实例代码:

祖先组件:

后代组件:

 

你可能感兴趣的:(vue.js,javascript,前端)