IT이야기

Vue.js - 도우미 기능을 단일 파일 컴포넌트로 글로벌하게 이용 가능

cyworld 2022. 5. 31. 07:48
반응형

Vue.js - 도우미 기능을 단일 파일 컴포넌트로 글로벌하게 이용 가능

Vue 2 프로젝트에는 다수의 (50개 이상의) 단일 파일 컴포넌트가 포함되어 있습니다.라우팅에는 Vue-Router를 사용하고 상태에는 Vuex를 사용합니다.

helpers.js 라고 하는 파일이 있습니다.이 파일에는 문자열의 첫 글자를 대문자로 하는 등 범용 함수가 많이 포함되어 있습니다.이 파일은 다음과 같습니다.

export default {
  capitalizeFirstLetter(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
}

main.js 파일은 을 초기화합니다.

import Vue from 'vue'
import VueResource from "vue-resource"
import store from "./store"
import Router from "./router"
import App from "./components/App.vue"

Vue.use(VueResource)

const app = new Vue({
  router: Router,
  store,
  template: '<app></app>',
  components: { App },
}).$mount('#app')

My App.vue 파일에는 다음 템플릿이 포함되어 있습니다.

<template>
  <navbar></navbar>
  <div class="container">
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // stuff
    }
  }
}
</script>

그런 다음 Vue-Router가 처리하는 여러 개의 단일 파일 컴포넌트가 있습니다.<router-view>태그를 지정합니다.

자, 예를 들어, 이 명령어를 사용할 필요가 있다고 합시다.capitalizeFirstLetter()SomeComponent.vue에 정의되어 있는 컴포넌트 내의 함수.그러기 위해서는 먼저 Import를 해야 합니다.

<template>Some Component</template>

<script>
import {capitalizeFirstLetter} from '../helpers.js'
export default {
  data() {
    return {
      myString = "test"
    }
  },
  created() {
    var newString = this.capitalizeFirstLetter(this.myString)
  }
}
</script>

모든 컴포넌트는 아니더라도 여러 컴포넌트로 기능을 Import하기 때문에 이 문제는 금방 발생합니다.이것은 반복적인 것처럼 보이며 또한 프로젝트를 유지하기가 더 어려워집니다.예를 들어 helpers.js나 그 안에 있는 함수의 이름을 바꾸려면 Import하는 모든 컴포넌트로 이동하여 Import 문을 변경해야 합니다.

요컨대 helpers.js 내의 함수를 글로벌하게 이용할 수 있도록 하는 방법.를 통해 컴포넌트 에서 호출할 수 있습니다.처음 Import 후 추가하지 않아도 됩니다.this함수의 이름을 지정하시겠습니까?기본적으로는 이 작업을 수행할 수 있습니다.

<script>
export default {
  data() {
    return {
      myString = "test"
    }
  },
  created() {
    var newString = capitalizeFirstLetter(this.myString)
  }
}
</script>

컴포넌트를 Import한 후 함수 이름에 추가할 필요 없이 컴포넌트 내부

당신이 설명한 것은 믹스인입니다.

Vue.mixin({
  methods: {
    capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1);
  }
})

이것은 글로벌 믹스인입니다.모든 컴포넌트는 이 기능을 통해capitalizeFirstLetter호출할 수 있습니다.this.capitalizeFirstLetter(...)컴포넌트 메서드에서 또는 직접 호출할 수 있습니다.capitalizeFirstLetter(...)컴포넌트 템플릿에 있습니다.

작업 예: http://codepen.io/CodinCat/pen/LWRVGQ?editors=1010

다음 문서를 참조하십시오.https://vuejs.org/v2/guide/mixins.html

그렇지 않으면 도우미가 플러그인으로 기능하도록 시도할 수 있습니다.

import Vue from 'vue'
import helpers from './helpers'

const plugin = {
  install () {
    Vue.helpers = helpers
    Vue.prototype.$helpers = helpers
  }
}

Vue.use(plugin)

고객님의 고객명helper.js다음과 같이 함수를 내보냅니다.

const capFirstLetter = (val) => val.charAt(0).toUpperCase() + val.slice(1);
const img2xUrl = (val) => `${val.replace(/(\.[\w\d_-]+)$/i, '@2x$1')} 2x`;

export default { capFirstLetter, img2xUrl };

또는

export default { 
  capFirstLetter(val) {
    return val.charAt(0).toUpperCase() + val.slice(1);
  },
  img2xUrl(val) {
    return `${val.replace(/(\.[\w\d_-]+)$/i, '@2x$1')} 2x`;
  },
};

다음으로 컴포넌트 내 어디에서나 사용할 수 있습니다.

this.$helpers.capitalizeFirstLetter()

또는 어플리케이션 내 모든 장소에서 다음을 사용합니다.

Vue.helpers.capitalizeFirstLetter()

상세한 것에 대하여는, 다음의 메뉴얼을 참조해 주세요.https://vuejs.org/v2/guide/plugins.html

새 믹스인을 만듭니다.

"src/mixins/generalMixin.js"

Vue.mixin({
  methods: {
    capitalizeFirstLetter(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }    
  }
})

그런 다음 main.js로 Import합니다.

import '@/mixins/generalMixin'

부터는 이렇게 하다, 하다, 하다, 하다 등의 기능을 할 수 .this.capitalizeFirstLetter(str) 내 컴포넌트 스크립트 없이this다음 중 하나:

<template>
    <div>{{ capitalizeFirstLetter('hello') }}</div>
</template>

쓰셔야 돼요.this기본 Vue 인스턴스에 메서드를 혼합했기 때문입니다.this이것은 적어도 미래의 Vue 개발에서 이해하기 쉬운 기능을 공유하기 위한 문서화된 방법입니다.

Webpack v4 사용

가독성을 위해 별도의 파일을 만듭니다(플러그인 폴더에 마이닝이 드롭되었습니다).@CodinCat 및 @digout 응답에서 재생됩니다.

//resources/js/plugins/mixin.js
import Vue from 'vue';
    
Vue.mixin({
  methods: {
    capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1),
    sampleFunction() {
      alert('Global Functions');
    },
  }
});

그런 다음 main.js 또는 app.js 파일을 Import합니다.

//app.js
import mixin from './plugins/mixin';

용도:

★★this.sampleFunction() ★★★★★★★★★★★★★★★★★」this.capitalizeFirstLetter().

렌더링 시 데이터 형식 지정 방법에만 관련된 경우 전역 필터를 사용하십시오.다음으로 문서의 첫 번째 예를 제시하겠습니다.

{{ message | capitalize }}
Vue.filter('capitalize', function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

좋은 질문입니다.조사 결과 vue-inject가 이 문제를 가장 잘 처리할 수 있는 것으로 나타났습니다.표준 vue 컴포넌트 로직 처리 방법과는 별도로 많은 함수 라이브러리(서비스)를 보유하고 있습니다.컴포넌트 메서드를 서비스 함수를 호출하는 위임자로 하는 것이 좋습니다.

https://github.com/jackmellis/vue-inject

'store'와 마찬가지로 main.js 파일로 Import하면 모든 컴포넌트에서 액세스할 수 있습니다.

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App)
})

언급URL : https://stackoverflow.com/questions/42613061/vue-js-making-helper-functions-globally-available-to-single-file-components

반응형