将 prop 传递给 vuejs mixin 但属性未定义

nun*_*nos 8 mixins vue.js vue-mixin

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

我做错了什么或者我还能如何克服这个问题?

mixins/BarMixin.js:

export default baz => {
  return {
    // my mixin code...
  }
}
Run Code Online (Sandbox Code Playgroud)

components/FooComponent.vue:

<script>
import BarMixin from '@/mixins/BarMixin.js'

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

然后我尝试使用它,如下所示:

pages/foo.vue

<template>
  <FooComponent :baz="true" />
</template>

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

Run Code Online (Sandbox Code Playgroud)

Sim*_*iel 0

无法动态地将参数传递给 Vue mixins。

但是,您可以使用此函数方法作为替代方法:

 function BarMixin(param) {
  return {
    data() {
      return {
       ....
      }
    }
    // your mixin code
  }
 }
Run Code Online (Sandbox Code Playgroud)