0

I have a 'commonLibrary.js' which I've imported into my Vue app.

A small snippet of this library (and a good example) is:

var defaultDecimalRounding=3

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

So whenver "formatNumber" is called, it returns a number to a decimal rounding, based on the variable "defaultDecimalRounding"

What I'd like to do is move this defaultDecimalRounding variable out of the commonLibrary.js and into my Vue App so it can be changed within the app.

I've created a Mixin, as follows:

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

But I can't seem to get my formatNumber function to read this defaultDecimalRounding Mixin.

I don't mind doing a code-rewrite for the commonLibrary.js, there's only a dozen or so functions in there, but it would be nice to know how to get VueJS and an imported JS library talking to each other for future projects.

edit commonLibrary.js is imported as:

import common from './scripts/common.js';
const commonLibrary = {
    install() {
        Vue.common = common
        Vue.prototype.$common = common
    }
}
Vue.use(commonLibrary)
1
  • how do you import and use commonLibrary.js ? show me the code Commented Feb 14, 2020 at 9:05

2 Answers 2

1

Do as following:

in 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));
}

in your vue app:

import { defaultDecimal } from "./common";

Vue.mixin({
  data: function() {
    return {
      defaultDecimal : defaultDecimal
    };
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks. Unfortunately it's done absolutely nothing. Sure I can now see "defaultDecimal" on my Mixin now, but changing it isn't having any effect on the results returned.
Ah, you are right :). I believe you have to use a global state for that purpose OR vuex. take a look at this: vuejs.org/v2/guide/state-management.html
0

Most likely you need to use this because defaultDecimalRounding is now defined in the Vue instance. So something like this.defaultDecimalRounding

1 Comment

Tried that, get "TypeError: Cannot read property 'defaultDecimalRounding' of undefined" error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.