본문 바로가기

Java Scripts/Vue.js

Vue : Global Component

728x90
  • Why and when you’d want to use global registration
  • 글로벌 등록을 사용하려는 이유와 시기
  • Automatic Registration
  • 자동등록
  • How to create an icon component and use it globally
  • 아이콘 구성 요소를 생성하고 전역적으로 사용하는 방법

 

Why Global Registration?

import and locally register it within another component so we could use it in that parent component’s template.

해당 상위 구성 요소의 템플릿에서 사용할 수 있도록 다른 구성 요소 내에서 가져오고 로컬로 등록합니다.

with local registration, the component is only available for use within the component in which it’s registered.

로컬 등록을 사용하면 해당 구성 요소는 등록된 구성 요소 내에서만 사용할 수 있습니다.

 

It would be more efficient to globally register this component.

이 구성요소를 전역적으로 등록하는 것이 더 효율적입니다.

 

Basic Global Registration

let’s start creating an icon component for our app, and we’ll see how we can quickly globally register it.

우리 앱의 아이콘 구성 요소를 만들기 시작하고 이를 전역적으로 빠르게 등록하는 방법을 살펴보겠습니다.

 

Create BaseIcon.vue

<template>
 <div>Icon</div>
 </template>
 
 <script>
 export default {
 }
 </script>
 
 <style scoped>
 </style>

 go into our main.js file, we can do the following two steps:

main.js 파일로 이동하면 다음 두 단계를 수행할 수 있습니다.

 

1. Import BaseIcon.vue import BaseIcon from ‘@/components/BaseIcon’

2. Globally register it Vue.component(‘BaseIcon’, BaseIcon)

 

Now our BaseIcon can be used throughout our entire application.

이제 BaseIcon을 전체 애플리케이션에서 사용할 수 있습니다.

 

Automatic Global Registration

globally registration 을 하고 싶은 component 를 아래 code 를 이용하여 자동으로 등록하게 한다.

 

Main.js

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

const requireComponent = require.context(
  './components',
  false,
  /Base[A-Z]\w+\.(vue|js)$/
)

requireComponent.keys().forEach(fileName => {
  const componentConfig = requireComponent(fileName)

  const componentName = upperFirst(
    camelCase(fileName.replace(/^\.\/(.*)\.\w+$/, '$1'))
  )

  Vue.component(componentName, componentConfig.default || componentConfig)
})

 

import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

upperFirst converts the first character of a string to upper case.

upperFirst는 문자열의 첫 번째 문자를 대문자로 변환합니다.

camelCase converts a string to camel case (camelCase isWritten likeThis)

CamelCase는 문자열을 Camel Case로 변환합니다. (like  camelCase)

 

 

require.context function allowe to pass in 3 arguments

require.context 함수를 사용하면 3개의 인수를 전달할 수 있습니다.

1. A directory to search within.
2. A flag indicating whether subdirectories should be searched, too.
3. A regular expression to match files against.

 

const requireComponent = require.context(
  './components',      //  the relative path of the directory to search
  false,                     // subdirectories will not be searched
  /Base[A-Z]\w+\.(vue|js)$/   // regular expression that searches for components starting with "Base" and ending in  .vue or .js
)

 

Fleshing out BaseIcon.vue

npm install feather-icons --save

 

The feather-icons library is basically a collection of symbols with a simple interface to render.

feather-icons library 는 기본적으로 간단한 렌더링 인터페이스를 갖춘 기호 모음입니다.

<script>
 	import feather from 'feather-icons'
 	export default {
 		computed: {
 			svg() {
 				return feather.icons['activity'].toSvg({ class: "icon"
		})
 	}
 	}
 }
 </script>

We get an icon from the icons dictionary by name.  아이콘 dictionary 에서 이름으로 아이콘을 얻습니다.

 And then, we use the toSvg method to get the SVG of the icon.  그런 다음 toSvg 메서드를 사용하여 아이콘의 SVG를 가져옵니다

The class property is a configuration option that we use to add a class attribute to the SVG.

클래스 속성은 SVG에 클래스 속성을 추가하는 데 사용하는 구성 옵션입니다.

<template>
 <div class="icon-wrapper" v-html="svg"></div>
</template>

The v-html attribute will replace the content of the div with the SVG code returned from the svg method. 

v-html 속성은 div의 내용을 svg 메소드에서 반환된 SVG 코드로 아래와 같이 대체합니다.

<div class="icon-wrapper">
 <svg xmlns="http://www.w3.org/2000/svg" width="24"
	height="24" viewBox="0 0 24 24" fill="none"
	stroke="currentColor" stroke-width="2" stroke-linecap="round"
	stroke-linejoin="round" class="feather feather-activity icon">
	<polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline>
</svg>
</div>

 

If we wanted to alter its size from the default 24px, we could pass them into BaseIcon lik so:

기본 24px에서 크기를 변경하려면 다음과 같이 BaseIcon에 전달할 수 있습니다.

<BaseIcon name="activity" width="48" height="48" />

 

Here’s the complete component with scoped styles

<template>
  <div class="icon-wrapper" v-html="svg"></div>
</template>

<script>
import feather from 'feather-icons'
export default {
  props: {
    name: String,
    width: {
      type: [Number, String],
      default: 24
    },
    height: {
      type: [Number, String],
      default: 24
    }
  },
  computed: {
    svg() {
      return feather.icons['users'].toSvg({
        class: 'icon',
        width: this.width,
        height: this.height
      })
    }
  }
}
</script>

<style scoped>
.icon-wrapper {
  display: inline-flex;
  align-items: center;
  color: rgba(0, 0, 0, 0.4);
  font-size: 1rem;
  font-weight: 600;
  margin-right: 6px;
}
.icon {
  stroke: currentColor;
  stroke-width: 2;
  stroke-linecap: round;
  stroke-linejoin: round;
  fill: none;
}
</style>

 

GitHub - feathericons/feather: Simply beautiful open-source icons

 

GitHub - feathericons/feather: Simply beautiful open-source icons

Simply beautiful open-source icons. Contribute to feathericons/feather development by creating an account on GitHub.

github.com

 

SVG Tutorial - SVG: Scalable Vector Graphics | MDN (mozilla.org)

 

SVG Tutorial - SVG: Scalable Vector Graphics | MDN

Scalable Vector Graphics, SVG, is a W3C XML dialect to mark up graphics.

developer.mozilla.org

 

Component Registration | Vue.js (vuejs.org)

 

Component Registration | Vue.js

Haven't migrated to Vue 3 yet? Explore Never-Ending Support for Vue 2 by HeroDevs Learn more

vuejs.org

Dependency Management | webpack

 

Dependency Management | webpack

webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.

webpack.js.org

Release lesson7-global-finish · Code-Pop/real-world-vue · GitHub

 

Release lesson7-global-finish · Code-Pop/real-world-vue

update feather-icons usage

github.com

 

'Java Scripts > Vue.js' 카테고리의 다른 글

Vue - Progress Bar : Axios Interceptors  (0) 2022.01.12
Vue : API calls with Axios  (0) 2022.01.08
Vue : Single File Component  (0) 2022.01.08
Vue : Nested Routes  (0) 2022.01.08
Vue : Dynamic Routing & History Mode  (0) 2022.01.08