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

标签 javascript vue.js mixins

我有以下混合:

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/

相关文章:

vue.js - 抛出新错误 ('Cyclic dependency' + nodeRep)

javascript - 如何使用带有链接支持的 lodash 和 typescript 的 mixins

javascript - 如何等待 _.each 循环与 ajax 调用完成?

javascript - 将值从一种模式传递到另一种模式

vue.js - Dexie.js table.name 不起作用,即使该表位于 tables 属性下

python - 使用混合时返回基类的签名

css - 使用 .LESS 从同一容器中的其他 2 个元素继承样式

javascript - Django-dashing 创建你自己的小部件

javascript - CSS 分离头表技巧 : keep verticall scrollbar on screen and last cell go full width

javascript - 如何使用 VueJS 动态添加属性?