How to access mixins in functional component in Vue?
我有以下混入:
1 2 3 4 5 6 7 | Vue.mixin({ computed: { $_styles() { return { backgroundColor:"red" } } } }) |
然后,我具有以下功能组件:
1 2 3 4 5 | <template functional> <!-- $_styles doesn't work --> </template> |
我实际上如何在功能组件内部访问全局变量(在这种情况下为
与一些简单的mixins一起使用的另一种解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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'}) |
现在使用
1 2 3 4 | <template functional> </template> |
但是,如果您的mixin使用任何依赖项,这将不起作用。
EDIT:另一种方法是代替mixin在渲染时计算.Vue组件中的值,而是由工厂预先计算该值并将该值添加为对象属性。访问功能组件中的属性比混入更容易。在您的示例中,将加载ajax调用,然后工厂将处理对象,并添加_styles作为属性。然后,您将访问props.myProp._styles。
您不能使用基于模板的功能组件来执行此操作,但是如果定义了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | Vue.mixin({ computed: { $_styles() { return { backgroundColor: 'red' } } } }) Vue.component('func-component', { functional: true, render (createElement, context) { const style = { height: '100px', width: '100px', ...context.parent.$_styles // get mixin styles from parent component } return createElement('div', { ...context.data, style // override context.data.style }, context.children) } }) new Vue({el: '#app'}) |
1 2 3 | <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"> <func-component></func-component> |