【问题标题】:vue component data and computed propertiesvue 组件数据和计算属性
【发布时间】:2019-01-27 15:42:26
【问题描述】:

我遇到以下问题。

我正在声明数据,我想在之前、当前和之后进行设置。

data () {
  return {
    notes: {
      ...
    },
    view: {
      dayCurrent: new Date(),
      dayBefore: new Date().setDate(this.view.dayCurrent.getDate() - 1),
      dayAfter: new Date().setDate(this.view.dayCurrent.getDate() + 1)
    }
  }
}

但是一旦我保存这个我得到以下错误

data() 中的错误:“TypeError:无法读取未定义的属性 'dayCurrent'”,就好像我的视图对象不存在一样。

这是为什么?如何设置并避免此类错误。

【问题讨论】:

  • 为什么不直接使用new Date.getDate 而不是this.view.dayCurrent
  • 请检查我更新的答案我做了一些改变,比如直接使用 Date 的构造函数而不是 setDate 方法
  • 发生这种情况是因为您试图引用当前正在初始化的对象。 Ana Liza Pandac 的回答是正确的,因为它在初始化期间删除了这个循环引用。

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

另一种解决方案是在 return 语句之外声明 dayCurrent 并在您的其他属性中引用它。

data () {
  const dayCurrent = new Date();
  return {
    notes: {
      ...
    },
    view: {
      dayCurrent: dayCurrent,
      dayBefore: new Date().setDate(dayCurrent.getDate() - 1),
      dayAfter: new Date().setDate(dayCurrent.getDate() + 1)
    }
  }
}

【讨论】:

  • 有效。我得到了时间戳,但它有效。谢谢。
  • 您建议的解决方案很好,但您应该将() 添加到getDate 方法并直接使用构造函数而不是setDate 方法
  • @BoussadjraBrahim 感谢getDate 提醒,我错过了那个。但是,至于直接使用Date构造函数会导致这个日期1970-01-01T00:00:00.027Z
  • @AnaLizaPandac 是的,目前我在浏览器控制台中测试它时遇到了这个问题,对不起
  • @BoussadjraBrahim 不用担心。
【解决方案2】:

我建议在挂载的钩子中初始化您的view 属性,如下所示:

data() {
    return {
      notes: {
        ...
      },
      view: {
        dayCurrent: '',
        dayBefore: '',
        dayAfter: ''
      }
    }
  },
  mounted() {
    this.view.dayCurrent = new Date();
    this.view.dayBefore = new Date(this.view.dayCurrent.getDate() - 1);

    this.view.dayAfter = new Date(this.view.dayCurrent.getDate() + 1)

  }

new Vue({
  el: '#app',

  data() {
    return {
      notes: {

      },
      view: {
        dayCurrent: '',
        dayBefore: '',
        dayAfter: ''
      }
    }
  },
  mounted() {
    this.view.dayCurrent = new Date();
    let d1 = new Date().setDate(this.view.dayCurrent.getDate() - 1);
    this.view.dayBefore = new Date(d1);
    let d2 = new Date().setDate(this.view.dayCurrent.getDate() + 1);
    this.view.dayAfter = new Date(d2)

  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{view.dayBefore}}</p>
  <p>{{view.dayCurrent}}</p>
  <p>{{view.dayAfter}}</p>
</div>

【讨论】:

  • 它有效,谢谢。我正在获取时间戳。我想我会创建一些计算属性并从中生成所需的字符串。
  • 请检查我更新的答案我做了一些改变,比如直接使用 Date 的构造函数而不是 setDate 方法
猜你喜欢
  • 2019-07-14
  • 2017-03-12
  • 2020-02-03
  • 2019-09-22
  • 1970-01-01
  • 2020-09-30
  • 2019-12-05
  • 2019-08-12
  • 1970-01-01
相关资源
最近更新 更多