【问题标题】:How to access mixins in functional component in Vue?如何在 Vue 中访问功能组件中的 mixins?
【发布时间】:2019-09-16 06:53:11
【问题描述】:

我有以下混合:

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

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

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

我如何实际访问全局变量,在这种情况下它是$_styles,在函数组件内部?

【问题讨论】:

  • 它不是一个全局变量。如果您搜索 "vue functional component access mixin computed",您可能会更幸运地找到答案
  • 我不知道为什么你会期望函数组件能够访问给定的计算属性..."they’re stateless (no reactive data) and instanceless (no this context)"
  • @Phil 我指的是 mixins/Vue.prototype 中的“全局”。例如,如果我做Vue.prototype.$_styles = {backgroundColor: 'red'},那么我应该如何访问$_styles。很抱歉没有澄清。
  • 在功能组件中,我可以访问context对象。是否有可能以某种方式改变这个上下文对象,以便我可以做context.$_styles = {...}。所以我的意思是全球性的。
  • 当然,它可以通过context.data.style 获得,但在这种情况下你不能使用基于模板的功能组件

标签: javascript vue.js mixins


【解决方案1】:

另一种使用一些更简单的 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>

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


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

【讨论】:

    【解决方案2】:

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

    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>

    【讨论】:

      猜你喜欢
      • 2019-04-04
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 2018-08-09
      • 1970-01-01
      • 2022-12-01
      • 2021-01-04
      • 1970-01-01
      相关资源
      最近更新 更多