openks / learn-vue

自定义组件文档
https://openks.github.io/learn-vue
0 stars 0 forks source link

moment 使用问题 #46

Open openks opened 7 years ago

openks commented 7 years ago

问题描述如下: image 点击左箭头往前一天并格式化为显示的样式 点击右箭头往后一天并格式化为显示的样式

同事是这样写的:

<div class="navBar">
    <p class="left" @click="beforeDay()"><img class="img1" src="../assets/images/jian_l@2x.png" /></p>
    <span class="day" @click="onCalendar()">{{newday}}</span>
    <p class="right" @click="nextDay()"><img class="img2" src="../assets/images/jian_r@2x.png" /></p>
</div>
export default {
  data() {
    return {
      newday: ""
    }
  },
  methods: {
    beforeDay() {
      var tmp = this.newday;
      var time3 = moment(tmp).subtract(1, 'd').format('dddd , MMMM DD');
      this.newday = time3;
    },
    nextDay() {
      var tmp = this.newday;
      var time4 = moment(tmp).add(1, 'd').format('dddd , MMMM DD');
      this.newday = time4;
    },
  },
  mounted() {
    this.newday = moment().format('dddd , MMMM DD');
  },
}

结果发现点击下一天的时候就变成了Friday , August 31正常情况下应该是Thursday , August 31 来找我请求帮助。

openks commented 7 years ago

我先看了代码发现事情不应该是这么搞的
完全可以使用filter解决格式问题
前一天后一天的事件只是加一天或者减一天而已。

<div class="navBar">
    <p class="left" @click="beforeDay()"><img class="img1" src="../assets/images/jian_l@2x.png" /></p>
    <span class="day" @click="onCalendar()">{{newday|format}}</span>
    <p class="right" @click="nextDay()"><img class="img2" src="../assets/images/jian_r@2x.png" /></p>
</div>
export default {
  data() {
    return {
      newday: ""
    }
  },
  filters: {
    format: function(value) {
      return moment(value).format('dddd , MMMM DD');
    }
  },
  methods: {
    beforeDay() {
      var tmp = this.newday;
      var time3 = moment(tmp).subtract(1, 'd');
      this.newday = time3;

    },
    nextDay() {
      var tmp = this.newday;
      var time4 = moment(tmp).add(1, 'd');
      this.newday = time4;
    },
  },
  mounted() {
    this.newday = moment();
  },
}