当我尝试将 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/