只是想知道,我有以下设置:
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/