jj008
jj008

Reputation: 1093

Vue Local Data Using Getter

I'm trying to set a data property (in Classroom) based on what's in the store (of Lesson). But I keep getting undefined. How can I get that value and set it in data?

Classroom.vue:

data(){
  return {
    selectedOption: this.currentLesson
  }
}

computed: Object.assign({},
  mapGetters({
    currentLesson: "lesson/current"
  })
)

lesson.js:

const state = {
  current: {}
}

const getters = {
  current(){
    return state.current
  },
}

index.js:

export default new Vuex.Store({
  modules: {
    lesson,
    user
  }
})

Upvotes: 3

Views: 3047

Answers (1)

jian
jian

Reputation: 1256

UPDATE:

The component's data function is called before the computed values are set up. So you cannot use computed properties inside data function. (That is reasonable, because some computed getters might rely on certain properties from data. It might cause infinite loops if we set up computed values before calling data).

In your case, if you want selectedOption to always be the same as currentLesson, then you don't need to put it in the component's local data, just use this.currentLesson directly in your view template.

However, if you just want to set up an initial value for selectedOption based on lesson/current, you can explicitly access it via:

selectedOption: this.$store.getters['lesson/current']

Or by using a lifecycle hook like created or mounted:

created () {
    this.selectedOption = this.$store.getters['lesson/current']
    // or `this.selectedOption = this.currentLesson` if you keep that mapped getter
}

Original answer:

currentLesson: "lesson/current" is the "namespaced getter" syntax. You need to set namespaced: true for your lesson store definition. Did you set that field when you export lesson.js?

Upvotes: 6

Related Questions