UNPKG

@kaokei/use-vue-service

Version:

Lightweight Vue 3 state management with dependency injection, inspired by Angular services.

2 lines (1 loc) 2.78 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("@kaokei/di"),o=require("vue");function b(e){const t=e,n=o.effectScope(!0);return t[S]=n,n}function _(e){return e[S]}function N(e){const t=e;if(t){const n=_(t);n&&(n.stop(),delete t[S])}}function h(e){const t=_(e);return t||b(e)}function C(e,t,n){return e&&e.forEach(r=>{r&&r.isCurrentBound(t)&&n.push(r.get(t)),r.children&&C(r.children,t,n)}),n}function D(e,t){const n=[];return C(t.children,e,n),n[0]}function O(e,t){const n=[];return C(t.children,e,n),n}function A(e){return e!==null&&typeof e=="object"}function V(e,t){return A(t)?o.reactive(t):t}function T(e){return N(e)}function j({container:e}){return t=>D(t,e)}function w({container:e}){return t=>O(t,e)}function E(e){let t;return e?t=e.createChild():t=new u.Container,t.bind(I).toDynamicValue(j),t.bind(g).toDynamicValue(w),t.onActivation(V),t.onDeactivation(T),t}const I=new u.Token("USE_REACT_SERVICE_FIND_CHILD_SERVICE"),g=new u.Token("USE_REACT_SERVICE_FIND_CHILDREN_SERVICES"),S=Symbol(),s="USE_VUE_SERVICE_CONTAINER_TOKEN",f=E();function a(e,t){if(typeof t=="function")t(e);else for(let n=0;n<t.length;n++)e.bind(t[n]).toSelf()}function R(){const e=o.getCurrentInstance();if(e){const t=s,n=e.provides,r=e.parent&&e.parent.provides;if(n&&n!==r&&Object.prototype.hasOwnProperty.call(n,t))return n[t]}}function v(){if(o.hasInjectionContext())return o.inject(s,f);throw new Error("getProvideContainer 只能在 setup 中使用")}function F(e){return(R()||v()).get(e)}function H(e){return f.get(e)}function L(e,t){return t.runWithContext(()=>v().get(e))}function U(e){const t=R();if(t)a(t,e);else{const n=v();let r=E(n);a(r,e),o.provide(s,r),o.onUnmounted(()=>{r.destroy(),r=null})}}function x(e){a(f,e)}function m(e,t){t.runWithContext(()=>{const n=o.inject(s,null);if(n)a(n,e);else{let r=E(f);a(r,e),t.provide(s,r),t.onUnmount(()=>{r.destroy(),r=null})}})}function K(e){return t=>m(e,t)}function q(e,t,n){const r=n.get,d=n.set;return{configurable:!0,enumerable:!0,get(){const c=o.reactive(this),l=Symbol.for(t);let i=c[l];if(!i){const y=h(c).run(()=>d?o.computed({get:()=>r.call(c),set:P=>d.call(c,P)}):o.computed(()=>r.call(c)));i=o.markRaw({value:y}),c[l]=i}return i.value.value},set(c){const l=o.reactive(this),i=Symbol.for(t),p=l[i];p&&d&&(p.value.value=c)}}}exports.Computed=q;exports.FIND_CHILDREN_SERVICES=g;exports.FIND_CHILD_SERVICE=I;exports.declareAppProviders=m;exports.declareAppProvidersPlugin=K;exports.declareProviders=U;exports.declareRootProviders=x;exports.getEffectScope=h;exports.getRootService=H;exports.useAppService=L;exports.useService=F;Object.keys(u).forEach(e=>{e!=="default"&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:()=>u[e]})});