2

Just wondering, I have the following setup:

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(),
      },
      ...
)}

As you can see, I'm trying to pass in (new Date()).getMonth() into the monthNames array from const - but console is returning the Uncaught TypeError: Cannot read property '4' of undefined.

So my question is simply: how do I reference monthNames from within data?

N.B. I'm using the most recent js dev build.

1
  • Have you found a solution by yourself or tested any of the answers? Did you find any bugs using them? Commented May 30, 2018 at 21:56

2 Answers 2

3

You could declare it outside the Vue instance or perhaps in another module and import it before using like import { monthNames } from './constants', and then use it whenever you want.

If you want to keep it inside that particular Vue instance then i think it would be better to put it inside the computed structure for caching.

Example:

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(),
  },
  ...
)

A question that matches yours: https://stackoverflow.com/a/46883212/7395911

A discussion about a constant structure within Vue: https://github.com/vuejs/vue/issues/6004

Sign up to request clarification or add additional context in comments.

1 Comment

The issue is, when I assign these constants to data and edit from form it gets changed.
0

I'm a newbie to Vue but you can attach it to the Vue simply by calling:

Vue.prototype.$monthNames

And then calling it within data using monthNames

From what I can find you can also use mixins (seems a bit dangerous, affects all components) or simply just declaring a constant before loading the Vue instance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.