我打算在整个 Vue.js 2 应用程序(即在组件和 vuex 中)中使用几个辅助函数。我在这里用作示例的 toCurrency
将数字转换为货币字符串。我想知道放置此辅助函数的最佳位置在哪里。我目前将它放在我的 store.js
文件的顶部(显然我正在使用 vuex
)并在整个文件中调用它。然而,这意味着当我想在组件中使用它时,我还需要将它定义为一个方法
。有没有更好的地方放置它们,这样我就不必一直定义它,或者这是最好的地方?
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))
}
}
})
最佳答案
这听起来像是 Instance Variables 的完美案例.本质上,我会首先设置一个地址,例如 this.$helperfunctions
,然后继续将我的所有方法直接添加到这个实例成员上,之后它们将可供您的应用程序的其余部分使用。
import myObjectFullOfMethods from '../somewhere/foo/bar.js';
new Vue({
beforeCreate: function() {
this.$helperfunctions = new myObjectFullOfMethods();
}
})
关于javascript - 在哪里放置全局帮助 js 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51623849/