【问题标题】:How to assign a function as a value to the property of an object in the Vuex State from a component?如何从组件将函数作为值分配给Vuex状态中的对象的属性?
【发布时间】: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


    【解决方案1】:

    动作和突变只接受两个参数:名称和有效负载。要传递多个值,您可以传递一个对象。

    this.$store.dispatch('newFullPageOption', {
       onLeave: 'onLeave',
       onLeaveCallback: onLeaveCallback
    })
    

    这可以用object property shorthand 写成如下,但它仍然只是两个参数。属性名称必须与同名的现有变量匹配:

    const onLeave = 'onLeave';
    this.$store.dispatch('newFullPageOption', { onleave, onLeaveCallback })
    

    在操作中,您会收到两个参数:上下文和有效负载。有效载荷可以是destructured,它看起来像反向的对象属性简写:

    NewFullpageOption(context, { onLeave, onLeaveCallback }){ // Destructuring
      // Mutations only take two arguments too:
      context.commit('setNewFullpageOption', { onLeave, onLeaveCallback })
    }
    

    突变使用相同的双参数格式:

    setNewFullpageOption(state, { onLeave, onLeaveCallback }){
       Vue.set(state.fullpage.options, onLeave, onLeaveCallback)
    }
    

    【讨论】:

    • 谢谢!正是我要找的:) 是的,我在写的时候更新了名字,而忽略了在问题中更新它,我会编辑这个问题,这样其他人就不会感到困惑了。感谢您的帮助!