【发布时间】:2026-01-21 21:30:01
【问题描述】:
我需要帮助将函数添加到对象的属性中,作为我的 Vuex 存储状态的值。
我目前正在使用 vue.js 和 fullpage.js 为网站重构一些代码 我将整页选项移至 vuex 商店,但在从子组件的选项中向 onLeave 回调添加方法时遇到问题。
我最初在主组件数据对象中有选项,并从同一组件传递了一个方法。
data{
return {
options:{
onLeave: this.morphScroll
}
}
},
methods: {
morphScroll(origin, destination, direction){
//do something
}
}
选项现在存在于 state 中,我将 fullpage 作为 prop 从父组件(home)传递给子组件。如果我通过使用$store.state.fullpage.options.onLeave = function 直接分配值来更改状态,那么它会按预期工作,并且我会看到在 vue 开发工具中分配的值。
当我尝试通过调度一个操作来进行更改时,我得到一个 undefined 分配给 onLeave 的值...我正在从 beforeCreate 生命周期挂钩调度。
//Action dispatched
this.$store.dispatch('newFullPageOption', 'onLeave', onLeaveCallback)
//Mutation to set the state
//where would be 'onLeave', val would be the function being passed
setNewFullpageOption(state, where, val){
Vue.set(state.fullpage.options, where, val)
}
//My action
newFullPageOption(context, where, val){
context.commit('setNewFullpageOption', where, val )
}
//Function I am passing to onLeave option
//It is being passed in the beforeCreate() lifecycle hook
const onLeaveCallback = (origin, destination, direction) => {
if( origin.index == 0 && direction == 'down') {
this.morphSVG.direction = 'normal'
this.morphSVG.play()
this.fpzindex = false
console.log('scroll down destination:', destination.index)
}
if( origin.index == 1 && direction == 'up') {
this.morphSVG.direction = 'reverse'
this.morphSVG.play()
this.fphidden = true
console.log('scroll up destination:', destination.index)
}
console.log('data from component:', this.testdata)
}
//this.$store.dispatch('newFullPageOption', 'onLeave', onLeaveCallback)
this.$store.state.fullpage.options.onLeave = onLeaveCallback
感谢任何帮助。谢谢。
【问题讨论】:
标签: javascript vue.js vue-component vuex fullpage.js