UNPKG

@idooel/runtime-context

Version:

Runtime data pool with namespaces, stackable contexts, subscriptions and optional persistence. Vue adapter included.

88 lines (74 loc) 2.27 kB
// Vue 2 集成使用示例 import Vue from 'vue' import { Vue2DataPoolPlugin, useDataPool, usePoolValue } from '@idooel/runtime-context/vue2' // 1. 安装插件 Vue.use(Vue2DataPoolPlugin, { // 可选配置 globalInject: true, // 全局注入 $dataPool mixin: true // 自动混入生命周期管理 }) // 2. 在组件中使用 new Vue({ el: '#app', data() { return { // 使用响应式数据池值 userInfo: null, theme: 'light' } }, created() { // 方式1: 直接使用全局数据池 const pool = this.$idooelDataPool pool.set('user', 'token', 'abc123') pool.set('app', 'theme', 'dark') // 方式2: 使用组合式 API (需要在函数组件或 setup 中) // const token = usePoolValue('user', 'token') // const theme = usePoolValue('app', 'theme') // 读取数据 this.userInfo = pool.get('user', 'profile') this.theme = pool.get('app', 'theme', 'light') // 订阅数据变更 pool.subscribe({ ns: 'user', key: 'profile' }, (event) => { this.userInfo = event.value }) }, methods: { updateUserProfile(newProfile) { this.$idooelDataPool.set('user', 'profile', newProfile) }, switchTheme() { const newTheme = this.theme === 'light' ? 'dark' : 'light' this.$idooelDataPool.set('app', 'theme', newTheme) this.theme = newTheme } }, template: ` <div> <div>当前主题: {{ theme }}</div> <div>用户信息: {{ userInfo }}</div> <button @click="switchTheme">切换主题</button> <button @click="updateUserProfile({ name: '张三', age: 25 })"> 更新用户信息 </button> </div> ` }) // 3. 在不同组件间共享数据 const ComponentA = Vue.extend({ created() { // 设置数据 this.$idooelDataPool.set('shared', 'message', '来自组件A的消息') } }) const ComponentB = Vue.extend({ created() { // 读取其他组件设置的数据 const message = this.$idooelDataPool.get('shared', 'message') console.log('收到消息:', message) // 响应式订阅 this.$idooelDataPool.subscribe({ ns: 'shared', key: 'message' }, (event) => { console.log('消息更新:', event.value) }) } })