javascript - vue.js 引用数据中的常量?

标签 javascript vue.js vuejs2

只是想知道,我有以下设置:

new Vue({
      el: '#app',
      const: {
        monthNames       : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
      },
      data: {
        year             : (new Date()).getFullYear(),
        month            : (new Date()).getMonth(),
        monthName        : this.monthNames[(new Date()).getMonth()],
        day              : (new Date()).getDate(),
      },
      ...
)}

如您所见,我尝试将 (new Date()).getMonth()const 传递到 monthNames 数组中code> - 但控制台返回未捕获的类型错误:无法读取未定义的属性“4”

所以我的问题很简单:如何从数据中引用月份名称

注意我正在使用最新的 js 开发版本。

最佳答案

您可以在 Vue 实异常(exception)部或另一个模块中声明它,并在使用之前导入它,例如 import {monthNames } from './constants',然后在需要时使用它。

如果您想将其保留在特定的 Vue 实例中,那么我认为最好将其放在 compulated 结构中进行缓存。

示例:

const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

new Vue({
  el: '#app',
  data: {
    year             : (new Date()).getFullYear(),
    month            : (new Date()).getMonth(),
    monthName        : monthNames[(new Date()).getMonth()],
    day              : (new Date()).getDate(),
  },
  ...
)

与您的问题相符的问题:https://stackoverflow.com/a/46883212/7395911

关于 Vue 中常量结构的讨论:https://github.com/vuejs/vue/issues/6004

关于javascript - vue.js 引用数据中的常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50536254/

相关文章:

javascript - 从字符串中解析数字并将其推送到数组中

javascript - 如何从此 Blogger 小部件中删除 document.write

javascript - 自动登录 facebook - FB.Event.subscribe auth.login 不起作用

javascript - VueJS - 如何在数据更改时滚动到底部

vue.js - 是否可以全局绑定(bind)到更改事件?

javascript - 不向需要参数的方法传递参数

vue.js - 状态更改时更新 getter 值 Vuex 存储

javascript - 多折线图 D3.js Json数据结构

javascript - 如何使用计算属性过滤 VueJS 中 v-for 循环的结果?

vue.js - 使用Vue CLI3.0创建多页应用程序,如何处理此错误?