Add dynamic date format to Momen.js in Vue

Viewed 39

I need to display the date format depending on saved settings. I call axios to check saved date format:

 axios
     .get('/api/user/')
     .then(response => (this.date_format = response.data.dateformat))

Then I added filters:

        filters: {
        moment: function (date) {
          return moment(date).format(this.date_format);
        }
      },

And display it in HTML:

<p class="card-title"> Date of Birth:
   <span[[dob | moment]]</span>
</p>

If I display [[data_format]] it shows correctly "DD/MM/YYYY". But when I try to console.log(this.date_format) console shows Undefined. How to replace FormatNeeded in return moment(date).format(FormatNeeded); with this.date_format?

1 Answers

I finally found out how to solve the problem. When I call API, I set date_format to a global variable (probably not the correct term):

            axios
            .get('/api/user/')
            .then(response => (this.date_format = response.data.dateformat))
            .then(response => (window.date_format = this.date_format))

Then in filters, I use window.date_format not this.date_format:

        filters: {
        moment(date) {
            var format_elem = window.date_format;
          return moment(date).format(format_elem);
        }
      }
Related