programing

글로벌 도우미 js 함수를 저장할 위치

sourcejob 2022. 7. 21. 23:37
반응형

글로벌 도우미 js 함수를 저장할 위치

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

인스턴스 변수에 대한 완벽한 사례인 것 같습니다.기본적으로 다음과 같은 주소를 먼저 설정합니다.this.$helperfunctions그런 다음 모든 메서드를 이 인스턴스 멤버에 직접 추가한 후 어플리케이션의 나머지 부분에서 사용할 수 있게 됩니다.

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

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

언급URL : https://stackoverflow.com/questions/51623849/where-to-put-global-helper-js-functions

반응형