programing

정적 콘텐츠(예: 국가 코드)를 vue.js 앱의 어디에 저장합니까?

prostudy 2022. 6. 1. 17:36
반응형

정적 콘텐츠(예: 국가 코드)를 vue.js 앱의 어디에 저장합니까?

이 문제에 대한 일반적인 베스트 프랙티스를 찾으려고 했지만 잘못된 곳을 찾고 있는 것 같습니다.vue.js 앱에 국가 코드 등의 콘텐츠(또는 카테고리 배열 등 기타 정적 콘텐츠)를 저장하는 모범 사례는 무엇입니까?그것을 환경변수로 .env 파일에 저장하는 것은 곤란합니다.또 다른 설정변수도 아닙니다.

사용자나 앱에 의해 변경되지 않는 불변의 데이터인데도 Vuex에 저장해야 합니까?아니면 js파일을 만들어서 필요한 곳에 Import하면 되나요?각진 상태JS는 HelperService에 함수로 넣었을 뿐인데...

function getCountryArray() {
        var countries = {
              'AF': 'Afghanistan',
              'AX': 'Åland Islands',
              'AL': 'Albania',
              'DZ': 'Algeria',
              'AS': 'American Samoa',
              'AD': 'Andorra',
              'AO': 'Angola',
              'AI': 'Anguilla',
              'AQ': 'Antarctica',
              'AG': 'Antigua and Barbuda',
              'AR': 'Argentina'
...

다음을 사용하여 모든 vue 인스턴스(컴포넌트)에서 모든 속성/기능에 액세스할 수 있도록 설정할 수 있습니다.Vue.prototype.

Vue.prototype.getCountries = {
  'AF': 'Afghanistan',
  'AX': 'Åland Islands',
  'AL': 'Albania',
  'DZ': 'Algeria',
  'AS': 'American Samoa'
};
 
Vue.component('test', {
  template: `<div>{{ getCountries }}</div>`,
  created() {
    console.log('countries ->', this.getCountries);
  }
})
 
new Vue({
  el: '#app',
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

<div id="app">
  <test />
</div>

또 다른 대안은 글로벌 믹스인을 정의하는 것으로, 같은 방법으로 동작합니다.

Vue.mixin({
  data() {
    return {
      get getCountries () {
        return {
         'AF': 'Afghanistan',
         'AX': 'Åland Islands',
         'AL': 'Albania',
         'DZ': 'Algeria',
         'AS': 'American Samoa'
      };
    }
  }
})

개인 취향

모든 컴포넌트에 불필요한 값을 과부하시키지 않기 위해 특정 컴포넌트(Vue Mixins)에서만 사용하기 위해 mixin을 Import할 수 있습니다.

mixin을 사용하도록 수정(글로벌 mixin이 아님)

let getCountriesMixin = {
  methods: {
    getCountries: function () {
      return {
        'AF': 'Afghanistan',
        'AX': 'Åland Islands',
        'AL': 'Albania',
        'DZ': 'Algeria',
        'AS': 'American Samoa'
      }
    }
  }
};

Vue.component('test1', {
  mixins: [getCountriesMixin],
  template: '<div>test1 {{ getCountries() }}</div>',
  created() {
    console.log('test1 component: countries ->', this.getCountries());
  }
})

new Vue({
  el: '#app',
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>

<div id="app">
    <test1><test1/>
</div>

언급URL : https://stackoverflow.com/questions/50587636/where-to-store-static-content-e-g-country-codes-in-a-vue-js-app

반응형