jillztom / vue-moments-ago

A Vue.js component for dynamically updating human readable time format.
13 stars 13 forks source link

Vue-moments-ago based on momentsjs functions and locales #4

Open pcrombach opened 5 years ago

pcrombach commented 5 years ago

Hi, I don't know why but I can't open a new Pull request. I have a very short but effective component code based on the functions moments has. This code uses the function fromNow in momentjs and it uses all locales from moments. As far as I tested this it works for all locale as it should be. Because the suffix 'ago' now is managed by the locales of moments there is no need use a coded argument/prop. Be aware that the local for Korean in moments is 'ko' not 'kr'. This solution solves a lot of specials which some locales (like german en french) have a prefix like (german:'vor', french:'il y a') for the suffix 'ago'. These exceptions are very difficult to manage with coding yourself. Like I said before if you don't want these changes I consider to publish this variant as a new npm module.

<template>
  <span v-if="date" class="vue-moments-ago">{{ prefix }} {{ ago }}</span>
</template>

<script>
import Vue from 'vue';
import moment from 'moment';
Vue.prototype.moment = moment;

export default {
  data() {
    return {
      ago: '',
      relativeTime: ''
    };
  },
  props: {
    prefix: {
      type: String,
      default: 'posted'
    },
    date: {
      type: String,
      required: true
    },
    lang: {
      type: String,
      default: 'en'
    }
  },

  mounted() {
    setInterval(() => {
      this.getAgo();
    }, 1000);
  },

  created() {
    this.getAgo();
  },

  methods: {
    getAgo() {
      this.ago = moment(this.date).locale(this.lang).fromNow();
    }
  }
};
</script>

<style scoped>
.vue-ago {
  font-size: 12px;
}
</style>
rrolla commented 4 years ago

@pcrombach That will be really great to use your package