如何通过 @storybook/addon-contexts 在 vue js 项目中使用 storybook 切换语言环境 [英] how to switch locale with storybook in vue js project via the @storybook/addon-contexts

查看:49
本文介绍了如何通过 @storybook/addon-contexts 在 vue js 项目中使用 storybook 切换语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找能够在故事书中从 vue-i18n 切换语言环境的示例.我找到了这个 addon-context story 在官方故事书 github 上,但我在制作作品时遇到了一些困难.

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.

我使用的是 storybook v5.3、vue.js v2.6 和 vue-i18n v8.15.4.

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

目前,我有 2 个条目(英语和法语)的地球图标.但是当我切换时,它对 vue-i18n 语言环境没有影响.

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" }
        }
      }
    ]
  }
];

推荐答案

经过一些尝试,我找到了一个可行的解决方案.注意:每个故事都由一个 div slot 组件包裹,该组件监视 addon-contexts 使用的 local 并设置 vue-i18n locale.

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" }
        }
      }
    ]
  }
];

等等!:)

这篇关于如何通过 @storybook/addon-contexts 在 vue js 项目中使用 storybook 切换语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆