how to switch locale with storybook in vue js project via the @storybook/addon-contexts

帅比萌擦擦* 提交于 2021-02-10 15:00:55

问题


I m looking for a sample to be able to switch locale from vue-i18n inside storybook. I have find this addon-context story on the official storybook github but i have some difficulties to make works.

I m using storybook v5.3, vue.js v2.6 and vue-i18n v8.15.4.

For the moment, i have the globe icon with 2 entries (english and french). But when i switch it has no effect on the vue-i18n locale.

// .storybook/main.js
module.exports = {
  stories: ["../../src/**/*.stories.(js|jsx|ts|tsx|mdx)"],
  addons: [
    // ...
    "@storybook/addon-contexts"
  ]
};
// .storybook/preview.js

// Storybook
import { withContexts } from "@storybook/addon-contexts/vue";
import { addDecorator, addParameters } from "@storybook/vue";
import { contexts } from "./contexts";

// Internationalisation
addDecorator(() => ({
  i18n,
  beforeCreate: function() {
    this.$root._i18n = this.$i18n;
  },
  template: "<story/>"
}));
addDecorator(withContexts(contexts));
// .storybook/contexts.js
export const contexts = [
  {
    icon: "globe",
    title: "Languages",
    params: [
      {
        name: "English",
        props: {
          value: { locale: "en" }
        }
      },
      {
        name: "French",
        props: {
          value: { locale: "fr" }
        }
      }
    ]
  }
];

回答1:


After some tries, i have found a working solution. Note: Each story is wrapped by a div slot component that watch the local used by the addon-contexts and sets the vue-i18n locale.

// .storybook/contexts.js
const createContext = (initialValue) => {
  return {
    name: `Context.i18n`,
    props: ["value"],
    watch: {
      value: function(newValue, oldValue) {
        this.$root._i18n.locale = newValue.locale;
      }
    },
    template: `<div><slot /></div>`
  };
};

const i18nContext = createContext({
  locale: "en"
});

export const contexts = [
  {
    icon: "globe",
    title: "Languages",
    components: [i18nContext],
    params: [
      {
        name: "English",
        props: {
          value: { locale: "en" }
        }
      },
      {
        name: "French",
        props: {
          value: { locale: "fr" }
        }
      }
    ]
  }
];

Et voilà ! :)



来源:https://stackoverflow.com/questions/60460548/how-to-switch-locale-with-storybook-in-vue-js-project-via-the-storybook-addon-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!