如何在 Vue 的功能组件中访问 mixin?

How to access mixins in functional component in Vue?

我有以下混入:

Vue.mixin({
    computed: {
        $_styles() {
            return { backgroundColor: "red" }
        }
    }
})

然后,我有以下功能组件:

<template functional>
    <!-- $_styles doesn't work -->
    <div style="height: 100px; width: 100px;" :style="$_styles">
    </div>
</template>

我如何实际访问全局变量,在本例中是 $_styles,在功能组件中?

您不能使用基于模板的功能组件执行此操作,但如果您定义了 render 函数,则可以操作 context.data.style 属性,包括从context.parent 组件。

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'})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="app">
  <func-component></func-component>
</div>

另一种适用于一些更简单的 mixins 的解决方案:

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>

但是,如果您的混入使用了任何依赖项,这将不起作用。


编辑: 另一种方法不是混合在渲染时计算 .Vue 组件中的值,而是工厂预先计算值并将该值作为对象添加属性。访问功能组件中的属性比混合更容易。在您的示例中,将加载 ajax 调用,然后工厂将处理对象,将 _styles 添加为 属性。然后您将访问 props.myProp._styles.