Skip to content

Commit

Permalink
Vue2: Fix play's within(canvas) by preserving #storybook-root
Browse files Browse the repository at this point in the history
  • Loading branch information
shilman committed Sep 15, 2022
1 parent 48e3af9 commit b8380fa
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions code/renderers/vue/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type { VueFramework } from './types';
export const COMPONENT = 'STORYBOOK_COMPONENT';
export const VALUES = 'STORYBOOK_VALUES';

const map = new Map<Element, Instance>();
const map = new Map<Element, [Instance, Element]>();
type Instance = CombinedVueInstance<
Vue,
{
Expand All @@ -21,11 +21,16 @@ type Instance = CombinedVueInstance<
Record<never, any>,
unknown
>;
const getRoot = (domElement: Element): Instance => {
const getRoot = (domElement: Element): [Instance, Element] => {
if (map.has(domElement)) {
return map.get(domElement);
}

// Create a dummy "target" underneath #storybook-root
// that Vue2 will replace on first render with #storybook-vue-root
const target = document.createElement('div');
domElement.appendChild(target);

const instance = new Vue({
beforeDestroy() {
map.delete(domElement);
Expand All @@ -37,13 +42,13 @@ const getRoot = (domElement: Element): Instance => {
};
},
render(h) {
map.set(domElement, instance);
map.set(domElement, [instance, target]);
const children = this[COMPONENT] ? [h(this[COMPONENT])] : undefined;
return h('div', { attrs: { id: 'storybook-root' } }, children);
return h('div', { attrs: { id: 'storybook-vue-root' } }, children);
},
});

return instance;
return [instance, target];
};

export const render: ArgsStoryFn<VueFramework> = (props, context) => {
Expand Down Expand Up @@ -92,7 +97,7 @@ export function renderToDOM(
}: RenderContext<VueFramework>,
domElement: Element
) {
const root = getRoot(domElement);
const [root, target] = getRoot(domElement);
Vue.config.errorHandler = showException;
const element = storyFn();

Expand All @@ -116,7 +121,7 @@ export function renderToDOM(
root[VALUES] = { ...element.options[VALUES], ...args };

if (!map.has(domElement)) {
root.$mount(domElement);
root.$mount(target);
}

showMain();
Expand Down

0 comments on commit b8380fa

Please sign in to comment.