月亮

[vue.js] vue3에서 filter 사용하기🤔 본문

vue.js

[vue.js] vue3에서 filter 사용하기🤔

듀네 2023. 5. 8. 22:45

저번에 선임님이 vue의 filter를 알아보라고 하셨는데 오늘 써볼 기회가 있어서 포스팅을 해보도록 하겠다.

 

 

일단 vue3에서 filter는 removed apis로 옮겨서 filter를 쓰기보단 computed나 method를 쓰기를 권장하고 있다!

 

하지만 그래도 쓰고 싶은 사람들을 위해 마이그레이션 가이드를 알려주고 있다.

https://v3-migration.vuejs.org/breaking-changes/filters.html#migration-strategy

 

Filters | Vue 3 Migration Guide

 

v3-migration.vuejs.org

 

한번 써보니까 vue3에서는 왜 filter를 없애는 건지 잘 모르겠는 느낌,,, filter 편한데,,,,

 

아무튼 vue3에서 filter를 쓰는 방법은 두가지로 정의하는 것 같다.

 

1. 지역적으로 쓸때 : computed나 method를 쓴다.

<template>
  <h1>Bank Account Balance</h1>
  <p>{{ accountInUSD }}</p>
</template>

<script setup>
  import { computed } from 'vue'

  const props = defineProps({
    accountBalance: {
      type: Number,
      required: true
    }
  })

  const accountInUSD = computed(() => {
    return '$' + props.accountBalance
  })
</script>

 

2. 전역적으로 쓸때 : app.config.globalProperties , $filters 사용

// main.js
import { currencyUSD } from "@/utils/filterUtils";

const app = createApp(App)

app.config.globalProperties.$filters = {
  currencyUSD
}
 //filterUtils.js
 export const currencyUSD = (value) => {
    return '$' + value
  }
//ListComponent.vue
<template>
  <h1>Bank Account Balance</h1>
  <p>{{ $filters.currencyUSD(accountBalance) }}</p>
</template>

 

 

 

참고 :

https://v3-migration.vuejs.org/breaking-changes/filters.html#migration-strategy

https://codeup-eugene.tistory.com/45

반응형
Comments