我正在尝试根据商店(课程)中的内容设置数据属性(在课堂中)。但我不断得到undefined。如何获取该值并将其设置在数据中?
Classroom.vue:
data(){
return {
selectedOption: this.currentLesson
}
}
computed: Object.assign({},
mapGetters({
currentLesson: "lesson/current"
})
)
Run Code Online (Sandbox Code Playgroud)
课程.js:
const state = {
current: {}
}
const getters = {
current(){
return state.current
},
}
Run Code Online (Sandbox Code Playgroud)
索引.js:
export default new Vuex.Store({
modules: {
lesson,
user
}
})
Run Code Online (Sandbox Code Playgroud)
更新:
data在设置计算值之前调用组件的函数。所以你不能在data函数内部使用计算属性。(这是合理的,因为一些计算得到的 getter 可能依赖于数据的某些属性。如果我们在调用 之前设置计算值,可能会导致无限循环data)。
在你的情况下,如果你想selectedOption总是和 一样currentLesson,那么你不需要把它放在组件的本地数据中,this.currentLesson直接在你的视图模板中使用即可。
但是,如果您只想为selectedOptionbased设置初始值lesson/current,则可以通过以下方式显式访问它:
selectedOption: this.$store.getters['lesson/current']
Run Code Online (Sandbox Code Playgroud)
或者通过使用生命周期钩子像createdor mounted:
created () {
this.selectedOption = this.$store.getters['lesson/current']
// or `this.selectedOption = this.currentLesson` if you keep that mapped getter
}
Run Code Online (Sandbox Code Playgroud)
原答案:
currentLesson: "lesson/current"是“命名空间getter”语法。您需要namespaced: true为课程存储定义进行设置。您在导出时设置了该字段lesson.js吗?
| 归档时间: |
|
| 查看次数: |
2229 次 |
| 最近记录: |