Skip to content

Vue3 reactive进行跨组件数据状态共享

vue2.6版本中可以使用Vue.observable进行跨组件数据状态共享,vue3中则使reactive来替换observable。以下进行简单应用情况的介绍。

测试项目基础结构

image.png

store文件下文件并编写相关状态数据和方法

import {reactive, readonly} from 'vue'

const initState = reactive({
  msg: 'default message'
})

export const state = readonly(initState)//--避免外部直接更改state值

export const mutations = {
  updateMessage(data){
    initState.msg = data
  }
}

组件中按需引入state和mutations去处理数据

以下仅仅对兄弟组件数据变化进行展示,其他情况下使用基本类似。在Home.vue中引入两个子组件Child1,Child2,并在其中进行数据简单操作。

  • Child1.vue

image.png

  • Child2.vue

image.png

  • Home中引入并观察数据变化 child1中点击按钮触发数据更新,可观察到child2数据对应更新

image.png

总结

以上为vue3中reactive进行简易数据状态管理的一个小例子。

Released under the MIT License.