首页 > 解决方案 > 使用 Nuxt Js i18n 在头部添加 RTL 条件

问题描述

我想添加一个条件如下

if(app.i18n.locale == 'ar')

我在这个项目中使用阿拉伯语和英语。如果当前语言是阿拉伯语,则在头部添加bootstrap-rtl.css,如果当前语言en调用bootstrap.css,我尝试了不止一种方法,没有成功。

标签: javascriptinternationalizationnuxt.jsright-to-lefthead

解决方案


例如在插件文件夹中添加一个文件direction-control.js

    export default ({ app }, inject) => {
    const dir = () =>
      app.i18n.locales.find((x) => x.code === app.i18n.locale)?.dir;
      inject('dir', dir);
    };

虽然您nuxt.config.js将需要与此类似的代码

  plugins: [
      '~/plugins/direction-control',  // your plugins file name
      // other plugins
    ],
    modules: [
    [
      'nuxt-i18n',
      {
        locales: [
          {
            code: 'en',
            file: 'en.json',
            dir: 'ltr',
            name: 'English',
          },
          {
            code: 'ar',
            file: 'ar.json',
            dir: 'rtl',        // that will be passed to your app
            name: 'عربي',
          },
        ],
        langDir: 'translations/',
        defaultLocale: 'ar',
      },
    ],
  ],

现在是时候获取目录了

export default {
  mounted() {
    console.log(this.$dir()); // logs your direction 'ltr' or 'rtl'
    console.log(this.$i18n.locale);
    if (this.$i18n.locale == "ar") {
       // make some action
    }
  },
}

或像这样的内部模板

<template>
  <div :dir="$dir()">
    <Nuxt />
  </div>
</template>

推荐阅读