美文网首页
elementPlus设置 locale 不生效 完美解决

elementPlus设置 locale 不生效 完美解决

作者: 魔仙堡杠把子灬 | 来源:发表于2021-08-12 17:13 被阅读0次

怕啥来啥

前端QQ群: 981668406
在此附上我的QQ: 2489757828 有问题的话可以一同探讨
我的github: 李大玄
我的私人博客: 李大玄
我的npm开源库: 李大玄
我的简书: 李大玄
我的CSDN: 李大玄
我的掘金: 李大玄
哔哩哔哩: 李大玄

正常写法 (我的代码不生效 ,你们的不知道,别犟)

//main.js
import ElementPlus, { locale } from 'element-plus';

import lang from 'element-plus/lib/locale/lang/zh-cn';

//2.------start
locale(lang)
//-------- end
const app = createApp(App);
// 1.
app.use(ElementPlus, { size: 'medium', locale: lang });

生效写法

import { createApp, ref } from 'vue'
import ElementPlus from 'element-plus';
import zhLocale from 'element-plus/lib/locale/lang/zh-cn';

import 'dayjs/locale/zh-cn';
ElementPlus.useLang = (app, ref, locale) => {
  const template = (str, option) => {
    if (!str || !option) return str
    return str.replace(/\{(\w+)\}/g, (_, key) => {
      return option[key]
    })
  }

  // 注入全局属性,子组件都能通过inject获取
  app.provide('ElLocaleInjection', {
    lang: ref(locale.name),
    locale: ref(locale),
    t: (...args) => {
      const [path, option] = args
      let value
      const array = path.split('.')
      let current = locale
      for (let i = 0, j = array.length; i < j; i++) {
        const property = array[i]
        value = current[property]
        if (i === j - 1) return template(value, option)
        if (!value) return ''
        current = value
      }
    },
  })
}


const app = createApp(App);
ElementPlus.useLang(app, ref, zhLocale)

相关文章

网友评论

      本文标题:elementPlus设置 locale 不生效 完美解决

      本文链接:https://www.haomeiwen.com/subject/lewlbltx.html