将全局助手js函数放在何处

时间:2018-08-01 00:40:13

标签: javascript vuejs2 vuex

我打算在整个Vue.js 2应用程序中(即在组件和vuex中)使用几个辅助函数。我在此处使用的示例toCurrency将数字转换为货币字符串。我想知道放置此辅助函数的最佳位置在哪里。我目前将其放在我的store.js文件的顶部(显然,我在使用vuex)并在整个文件中调用它。但是,这意味着当我想在组件中使用它时,还需要将其定义为method。有没有更好的放置它们的地方,所以我不必继续定义它还是这是最好的地方?

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

function toCurrency(num){
    return "$" + num.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}

export default new Vuex.Store({
    state: {
        price: 2
    },
    getters: {
        numString: state => {
            return toCurrency(state.funds)
        }
    },
    mutations: {
        decrementOne: state => {
            state.num --;
            alert("Price decremented to " + toCurrency(state.funds))
        }
    }
})

1 个答案:

答案 0 :(得分:2)

这听起来像是Instance Variables的完美案例。本质上,我首先会设置一个地址,例如this.$helperfunctions,然后继续将我的所有方法直接添加到该实例成员上,之后它们将对您的应用程序的其余部分可用。

import myObjectFullOfMethods from '../somewhere/foo/bar.js';

new Vue({
  beforeCreate: function() {
    this.$helperfunctions = new myObjectFullOfMethods();
  }
})
相关问题