Search code examples
vue.jsstorybook

Vue storybook globalTypes not re-rendering preview


Hello all i am currently in the process to integrate Storybook-Vue into my own pattern-lib. So far everything worked like a charm. Expect for one thing and that is adding a globalType in the preview.js and then using it inside a decorators. Registering the new Global type works, i see it in the toolbar but when i change the selected value it does not re-render the preview.

My first guess is that the context is not an observable object so Vue never knows when this object actually gets an update. But i am not sure how i could change this.

enter image description here

// preview.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n);

export const globalTypes = {
    locale: {
        name: 'Locale',
        description: 'Internationalization locale',
        defaultValue: 'en-US',
        toolbar: {
            icon: 'globe',
            items: [
                { value: 'de-DE', right: '🇩🇪', title: 'German' },
                { value: 'en-US', right: '🇺🇸 ', title: 'English' },
                { value: 'cs-CZ', right: '🇨🇿', title: 'Czech' },
                { value: 'zh-CN', right: '🇨🇳', title: 'Chinese' },
            ],
        },
    },
};

const localeSelect = (story, context) => {
    const wrapped = story(context)
    const locale = context.globals.locale
    return Vue.extend({
        components: { wrapped, BiToast },
        data () {
            return {
                locale
            }
        },
        watch: {
            locale: {
                deep: true,
                handler (val) {
                    this.$i18n.locale = val
                }
            }
        },
        template: `
                <div>
                    {{ locale }}
                    <wrapped/>
                </div>
            `
    })
}

export const decorators = [localeSelect]

Solution

  • Finally got it working. I just had to use useGlobals and set i18n outsite of the returned object.

    import { useGlobals } from '@storybook/client-api';
    
    const localeSelect = (story, context) => {
        const [{locale}] = useGlobals();
        i18n.locale = locale
        return Vue.extend({
        ...