定义vue.js计算属性的帮助方法



我正在使用带有vuex模块的vue.js。在几乎每个模块中,我都有一个动作&称为updateProp的突变,看起来像这样:

updateProp ({commit}, payload) {
  commit('updateProp', payload)
}
updateProp (state, payload) {
  state[payload.propName] = payload.newVal
}

因此,当我定义一些计算的属性时,该属性在Vuex中我写的源:

myComputedValue: {
  get () {
    return this.$store.state.vuexModuleName.propertyName
  },
  set (newValue) {
    this.$store.dispatch('vuexModuleName/updateProp', {propName: 'propertyName', newVal: newValue})
  }
}

通常我必须定义这样的多个计算值,所以我想我会创建一个全局助手方法:

Vue.prototype.$computedDefHelper = (computedPropModel, computedPropName) => {
  return {
    get () {
      return this.$store.state[computedPropModel][computedPropName]
    },
    set (newVal) {
      this.$store.dispatch(`${computedPropModel}/updateProp`, {propName: computedPropName, newVal: newVal})
    }
  }
}

因此,我将能够以较短的方式定义这些计算值:

myComputedValue: this.$computedDefHelper('vuexModuleName', 'propertyName')

但这不起作用 - 我遇到了一个错误,即$computedDefHelper不是一个函数 - 尝试了各种诸如混合/插件/非箭头功能等的方法,但似乎没有任何作用 - 甚至可能吗?

任何技巧都将不胜感激。

编辑:

目前我将其设置为工作的唯一方法是将其定义为助手,并在我想使用的每个模块中导入它:

import { computedDefHelper } from '@/helpers/globalHelpers'

因此,我可以使用它来定义计算值:

myComputedValue: computedDefHelper('vuexModuleName', 'propertyName')

,但我想避免导入它,并在每个组件中都已经内置(全球)。

编辑2:

我认为这可能与触发/lifecycle vue.js的内容有关,因为如果我在created挂钩中登录此方法,它看起来不错,所以可能与这些计算方法对象定义以某种方式分析的可能是与之相关的。比该全局方法注册了吗?

编辑3:

我已经快速创建了一个更简单的版本,我想在Code Sandbox上实现的目标(不起作用)以播放:https://codesandbox.io/s/x3661n317o

您可以在globalhelpers.js中定义mixin方法,例如 updater

const computedDefHelper = {
  install(Vue, options) {
    Vue.mixin({
      methods: {
        updater: function(name, payload) {
          return this.$store.dispatch(`${name}/updateProp`, payload);
        }
      }
    });
  }
};
export default computedDefHelper;

然后将其导入您的主体:

import computedDefHelper from '@/helpers/globalHelpers';
Vue.use(computedDefHelper);

您现在可以在这样的每个组件中使用它:

this.updater('vuexModuleName', payload)

可以根据您想要的参数重新设计payload

我认为您需要为此创建一个插件,并使用这样的vue实例安装此助手属性:

  import computedDefHelper from '@/helpers/globalHelpers'
  const Plugin = {
    install: (myVue, options) => {
      const aVue = myVue;
      aVue.prototype.$computedDefHelper = computedDefHelper;
    },
  };
  export default Plugin;

和您的main.js文件中的文件:

Vue.use(Plugin);

最新更新