【问题标题】:How to access VueJS Mixin within imported JS Library如何在导入的 JS 库中访问 VueJS Mixin
【发布时间】:2020-05-30 00:44:09
【问题描述】:

我有一个“commonLibrary.js”,已导入到我的 Vue 应用程序中。

这个库的一个小sn-p(也是一个很好的例子)是:

var defaultDecimalRounding=3

function formatNumber(number) {
    if (isNaN(number.value) == true) { return '-' }
    return numberWithCommas(parseFloat(number.value, 2).toFixed(defaultDecimalRounding));
}

因此,每当调用“formatNumber”时,它都会根据变量“defaultDecimalRounding”返回一个十进制舍入的数字

我想做的是将这个 defaultDecimalRounding 变量从 commonLibrary.js 中移到我的 Vue 应用程序中,以便可以在应用程序中进行更改。

我已经创建了一个 Mixin,如下:

Vue.mixin({
    data: function () {
        return {
            get defaultDecimalRounding() { return 3 },
        }
    },
});

但我似乎无法让我的 formatNumber 函数读取这个 defaultDecimalRounding Mixin。

我不介意对 commonLibrary.js 进行代码重写,那里只有十几个函数,但如果知道如何让 VueJS 和导入的 JS 库相互通信,那就太好了未来的项目。

编辑 commonLibrary.js 被导入为:

import common from './scripts/common.js';
const commonLibrary = {
    install() {
        Vue.common = common
        Vue.prototype.$common = common
    }
}
Vue.use(commonLibrary)

【问题讨论】:

  • 如何导入和使用commonLibrary.js?给我看代码

标签: javascript vue.js vue-mixin


【解决方案1】:

执行以下操作:

在 common.js 中

var defaultDecimalRounding = 3;

// use another name for export cause previous name  already is declared
export const defaultDecimal = defaultDecimalRounding;

function formatNumber(number) {
    if (isNaN(number.value) == true) { return '-' }
    return numberWithCommas(parseFloat(number.value, 2).toFixed(defaultDecimalRounding));
}

在你的 vue 应用中:

import { defaultDecimal } from "./common";

Vue.mixin({
  data: function() {
    return {
      defaultDecimal : defaultDecimal
    };
  }
});

【讨论】:

  • 嗨,谢谢。不幸的是,它什么也没做。当然,我现在可以在我的 Mixin 上看到“defaultDecimal”,但更改它对返回的结果没有任何影响。
  • 啊,你是对的:)。我相信您必须为此目的使用全局状态或 vuex。看看这个:vuejs.org/v2/guide/state-management.html
【解决方案2】:

您很可能需要使用 this,因为 defaultDecimalRounding 现在已在 Vue 实例中定义。所以像this.defaultDecimalRounding

【讨论】:

  • 试过了,得到“TypeError: Cannot read property 'defaultDecimalRounding' of undefined”错误
猜你喜欢
  • 2017-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 2017-01-18
  • 2017-06-09
  • 1970-01-01
  • 2022-01-08
相关资源
最近更新 更多