首页 > 解决方案 > 计算属性和 Vue 组件

问题描述

我正在尝试为现有的普通 JS 库开发一个 Vue 包装器组件。

库被传递一个回调,当它想要另一项数据时调用它,并且需要这个回调来返回该数据。

包装器组件不需要知道这些数据,实际的计算或检索将在顶层 Vue Application 中处理。

我认为我正在寻找的是一个计算属性。

但是我找不到在组件中定义计算属性的位置以及在父应用程序中处理实际计算的示例。

这就是我到目前为止所拥有的。(简化代码以保持简单)

在普通的 JS 库中:

export default (pullDataCallback) => {
    // the repaint method gets called at regular intervals
    const repaint = () => {
        // ... render the current frame of animation ...
        newData = pullDataCallback();
    };

    return {
        // ... a bunch of other methods ...
    };
};

我的 Vue 包装器组件:

Vue.component('vue-wrapper', {
    'template': '<div class="vue-wrapper"></div>',
    'computed': {
        'dataPair': SOMETHING
    },
    'mounted': () => {
        this.plainJSLibrary = require('plain-js-lib')(() => {
            return this.dataPair
        });
    },
});

顶级 Vue 应用程序

new Vue({
    'el': '#vue-wrapper',
    'computed': {
        'dataPair': () => {
            // simplified example calculation
            return { 'x': 23, 'y': 42 };
        }
    }
});

如您所见,目前我的组件代码中存在一些相当大的漏洞……任何对 Vue 更有经验的人都可以填补这些空白。

标签: javascriptvue.jsvuejs2computed-properties

解决方案


推荐阅读