Search code examples
javascriptvue.jsmomentjsvue-cli

How to use Moment.js in vuecli


I have npm installed vue-moment. I need to pass date to p tag via for loop. Also I need to create a method where i can add number of days to my date so that it will shoe the date after that number of days. How do i do it OR where am I wrong

main.js code:

Vue.use(require("vue-moment"));

vuecomponent code:

<template>
  <div>
    <div>
      <span>{{ new Date() | moment("MM.DD.YY") }}</span>
    </div>
    <p v-for="data in printdata" :key="data.index" v-html="data.name"></p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      printdata: [
        {
          name: "paraone"
        },
        {
          name: "<span>{{ new Date() | moment('MM.DD.YY') }}</span>"
        },
        {
          name: "parathree"
        },
        {
          name: "parafour"
        }
      ]
    };
  },
  components: {},

  methods: {
    changeDate: function() {
      var todaydate = new Date();
      moment(todaydate).format("YYYY-MM-DD");
      this.printdata[0].name = todaydate;
    }
  },
  created() {
    this.changeDate();
  }
};
</script>

<style lang="scss" scoped></style>

The one in div tag is working as expected but how do i get date in second p tag?


Solution

  • I got to know where I was wrong. I had not imported moment in the script tag of component. I had to do this

    <script>
    import * as moment from "moment/moment";
    export default {
      data() {
        return {
          printdata: [
            {
              name: "paraone"
            },
            {
              name: "<span>{{ new Date() | moment('MM.DD.YY') }}</span>"
            },
            {
              name: "parathree"
            },
            {
              name: "parafour"
            }
          ]
        };
      },
      methods: {
        changeDate: function() {
          var todaydate = new Date();
          moment(todaydate).format("YYYY-MM-DD");
          this.printdata[0].name = todaydate;
        }
      },
      created() {
        this.changeDate();
      }
    };
    </script>
    

    and now its working fine.