如何从组件将函数作为值分配给 Vuex 状态中对象的 属性?

How to assign a function as a value to the property of an object in the Vuex State from a component?

我需要帮助将一个函数添加到对象的 属性 作为我的 Vuex 存储状态的值。

我目前正在使用 vue.js 和 fullpage.js 重构网站的一些代码 我将我的整页选项移到了 vuex 商店,但我无法从子组件向我的选项中的 onLeave 回调添加方法。

我最初在 home 组件数据对象中有选项,并从同一组件传递了一个方法。

data{
  return {
    options:{
      onLeave: this.morphScroll
    }
  }
},
methods: {
   morphScroll(origin, destination, direction){
     //do something
   }
}

选项现在存在于状态中,我将 fullpage 作为 prop 从父组件 (home) 传递到子组件。如果我通过直接使用 $store.state.fullpage.options.onLeave = function 分配值来更改状态,那么它会按预期工作,我会在 vue 开发工具中看到分配的值。

当我尝试通过分派操作进行更改时,我得到了分配给 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

感谢任何帮助。谢谢。

Actions 和 mutations 只接受两个参数:名称和负载。要传递多个值,您可以传递一个对象。

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

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

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

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

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)
}