我有以下混合:
Vue.mixin({
computed: {
$_styles() {
return { backgroundColor: "red" }
}
}
})
然后,我有以下功能组件:
<template functional>
<!-- $_styles doesn't work -->
<div style="height: 100px; width: 100px;" :style="$_styles">
</div>
</template>
我如何实际访问功能组件内部的全局变量,在本例中为 $_styles
?
最佳答案
另一种适用于一些更简单的 mixin 的解决方案:
Vue.mixin({
computed: {
$_styles() {
return { backgroundColor: 'red' }
}
}
})
Vue.component('func-component', {
functional: true,
mixins: [styles],
stylesMixin() {
// grab styles from mixin using this.computed.
return this.computed._styles()
},
render (createElement, context) {
...
}
})
new Vue({el: '#app'})
现在使用$options
访问本地stylesMixin函数
<template functional>
<div style="height: 100px; width: 100px;" :style="$options.stylesMixin()">
</div>
</template>
然而,如果你的 mixin 使用了任何依赖项,这将不起作用。
编辑:另一种方法不是混合在渲染时计算 .Vue 组件中的值,而是工厂预先计算值并将该值添加为对象属性。访问功能组件中的属性比混合更容易。在您的示例中,将加载 ajax 调用,然后工厂将处理对象,添加 _styles 作为属性。然后您将访问 props.myProp._styles。
关于javascript - 如何在 Vue 的功能组件中访问 mixin?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57951703/