bytedance / magic-microservices

Make Web Components easier and powerful!😘
MIT License
576 stars 51 forks source link

readme.md vue demo problem #25

Open ponkans opened 1 year ago

ponkans commented 1 year ago

The problem:

A caveat to readme.md's vue demo is that if a module is reused more than once on the same page, vueInstance can be shared more than once. react won't have this problem because the reatc update is based on container, which is unique.

import Vue from 'vue/index';
import App from './component/Hello.vue';

let vueInstance = null;

export async function bootstrap() {
  console.log('vue app bootstraped');
}

export async function mount(container, props) {
  console.log('magic-microservices-component-vue mount >>> ', props);
  vueInstance = Vue.createApp({
    ...App,
    data() {
      return props;
    },
  }).mount(container);
}

export async function updated(attrName, value) {
  console.log('magic-microservices-component-vue update', attrName, ' >>> ', value);
  vueInstance[attrName] = value;
  vueInstance.$forceUpdate();
}

export async function unmount() {
  console.log('vue app will unmount');
}

hack:

import { createApp } from 'vue';
import App from './App.vue';

/**
 * Multiple vue instances are identified by container as unique identifiers
 */
const vueInstanceMap = new WeakMap();

export async function mount(container: Element, props: any) {
  const vueInstance = createApp({
    ...App,
    data() {
      return props;
    },
  }).mount(container);
  vueInstanceMap.set(container, vueInstance)
}

export async function updated(attrName: string, value: any, container: Element,) {
  const vueInstance = vueInstanceMap.get(container);
  vueInstance[attrName] = value;
  vueInstance.$forceUpdate();
}

export function unmount(magicInstance: any, container: any) {
  const vueInstance = vueInstanceMap.get(container);
  vueInstance.unmount();
}
divikshrivastava commented 11 months ago

Can I take a stab at this ? @jerryOnlyZRJ @erjanmx @jijiaxin1808 @ChelesteWang @h-a-n-a @0xflotus