vue.js - 将 prop 传递给 vuejs mixin 但属性未定义

标签 vue.js mixins vue-mixin

当我尝试将 prop 传递给 mixin 时,我得到一个 Cannot read property of undefined error .

我做错了什么或者我怎么能克服这个?
mixins/BarMixin.js :

export default baz => {
  return {
    // my mixin code...
  }
}
components/FooComponent.vue :
<script>
import BarMixin from '@/mixins/BarMixin.js'

export default {
  mixins: [BarMixin(this.baz)],
  props: {
    bar: {
      type: Boolean,
      required: true,
    },
  },
}
</script>

然后我尝试使用它,如下所示:
pages/foo.vue
<template>
  <FooComponent :baz="true" />
</template>

<script>
import FooComponent from '@/components/FooComponent.vue'
export default {
  components: {
    FooComponent,
  },
}
</script>

最佳答案

您可以通过从组件访问这些属性来解决方法,就像混合是组件一样。
要使属性“动态”,您可以在 mixin 中传递您需要访问的字段的名称。
像这样:

function myMixin(propName) {
  return {
    computed: {
      mixinComputed () {
        return this[propName] + 'somethingElse';
      }
    }
  };
}
如果要将对象的内部属性(例如“user.name”)传递给 mixin,可以在外部组件上创建一个计算项,或者将其置于 mixin 内部:
function myMixin(propName1, propName2) {
  return {
    computed: {
      mixinComputed () {
        return this.parsedPropValue1 + this.parsedPropValue2;
      },
      parsedPropValue1 () {
        return this.parsePath(propName1);
      },
      parsedPropValue2 () {
        return this.parsePath(propName2);
      }
    },
    methods: {
      parsePath(path) {
        if (!path)
         return;
        const split = path.split('.');
        return split.reduce((acc, curr) => acc && acc[curr], this);
      }
    }
  };
}
用法:
mixins: [myMixin('user.address.street', 'obj')]

关于vue.js - 将 prop 传递给 vuejs mixin 但属性未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58997396/

相关文章:

javascript - 合并具有相同第一个键值的对象,因此其余键值将添加到合并对象中

css - SASS Mixin 未产生预期结果

javascript - 如何使用 Vue 实例中的全局混合方法

javascript - Vue.js Import mixin 不在应用程序中导入

language-agnostic - 目前支持 mixins 的语言有哪些?

vue.js - mixin 函数中最好的命名约定是什么?

vue.js - 在替换为即将到来的数据 Vuejs 和 vue-infinite-loading 列表之前保留当前数据列表

javascript - 对子组件 Vue.js 的 props 数组进行排序

javascript - 观察者是否与 Vue 中的全局混合一起工作?

css - & 作为 LESS 中 mixin 的 sibling