【问题标题】:Change moment locale on runtime globally (make Vue.prototype.moment reactive)全局更改运行时区域设置(使 Vue.prototype.moment 具有响应性)
【发布时间】:2020-02-07 11:59:33
【问题描述】:

我正在像这样将时刻导入 Vue:

import moment from 'moment-timezone/builds/moment-timezone-with-data-2012-2022';
Vue.prototype.moment = moment;

然后在我的created() 中设置我想要的语言。 请记住,这适用于刷新,但不适用于运行时

export default new Vue({
   render: h => h(BaseApp), 

   mounted() {

      let supportedLanguages = ['tr', 'etc'];

      supportedLanguages.forEach((val) => {
            moment.locale(val, {
                months: this.$i18n.messages[val]._months_,
                monthsShort: this.$i18n.messages[val]._months_short_,
                monthsParseExact: true,
                weekdays: this.$i18n.messages[val]._weekdays_,
                weekdaysShort: this.$i18n.messages[val]._weekdays_short_,
                weekdaysMin: this.$i18n.messages[val]._weekdays_min_,
                weekdaysParseExact: true,
            });
        })

   },

   methods: {
       changeLocale(lang) {
          this.moment.locale(lang);
       }
   }
})

但是,在我的控制台中,如果我尝试 $vm0.moment.locale() 它会返回正确的语言环境

在我所有的组件中,我都在模板中使用它

<h1>{{ day.format('ddd') }}</h1>

问题是,当我尝试更改时刻的语言环境时,它并没有在每个组件的模板中更改。有没有办法在所有模板中强制刷新。 (我在 root 中尝试了$vm.$forceUpdate()

我怎样才能让时刻变得被动?

【问题讨论】:

    标签: javascript vue.js ecmascript-6 momentjs


    【解决方案1】:
    Two-way data binding by VueJS. It's not moment problem.
    
    var parent = new Vue({
      data: {
        a: 1
      }
    })
    // $addChild() is an instance method that allows you to
    // programatically create a child instance.
    var child = parent.$addChild({
      inherit: true,
      data: {
        b: 2
      }
    })
    console.log(child.a) // -> 1
    console.log(child.b) // -> 2
    parent.a = 3
    console.log(child.a) // -> 3
    

    【讨论】:

    • 嗯..如何实现我正在尝试的?你的代码块在这里解释什么?
    • 要更改每个组件的模板,您应该更改父级的数据。
    • 这不是在我的根目录中执行this.moment.locale(lang) 吗?
    • 不。它不会改变每个组件的模板。
    • 如果你不介意解释,如何让它反应?
    【解决方案2】:

    全局更改 Moment.js 上的区域设置不会更改现有时刻实例的区域设置。即使这样做了,也不会触发更新,因为 Vue 不会跟踪这些更改。

    我会建议使用 global mixin 的不同解决方案,其方法是在时刻实例上本地设置语言环境。

    import Vue from 'vue';
    
    Vue.mixin({
        methods: {
            formatDate (moment, format) {
                return moment
                    .locale(this.$root.locale)
                    .format(format);
            },
        },
    });
    
    export default new Vue({
        render: h => h(BaseApp),
        data: {
            locale: 'en'
        },
        methods: {
            changeLocale(locale) {
                this.locale = locale;
            }
        }
     });
    

    您的内联模板代码仍然具有同样的可读性。但是,在解决您的问题的同时,这也是一个更灵活的解决方案,它不关心时刻实例的来源。

    <h1>{{ formatDate(day, 'ddd') }}</h1>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2017-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多