programing

VueJ - VueX 및 플래시 메시지

javaba 2022. 8. 8. 19:29
반응형

VueJ - VueX 및 플래시 메시지

플래시 알림에는 VueJ2, VueX, NuxtJ 및 Vue-Snotify(artemsky/vue-snotify)를 사용합니다.

VueX의 올바른 사용은 아닐 수 있지만, 시행/캐치에서 발견된 오류를 디스패치하고 싶습니다.

try {
    throw new Error('test')
} catch (error) {
    this.$store.dispatch('errorHandler', error)
}

그런 다음 VueX를 사용한 디스패치에서는 오류가 여러 개 있을 경우 루프가 포함된 Notify-View 알림이 표시됩니다.

actions: {
    async errorHandler (error) {
        this.$snotify.error(error)
        // and if multiple errors, then while on error
    }
}

VueX에서 $snotify 인스턴스를 복구하는 방법과 생각은 어떻습니까?

나빠

Vue 스토어 초기화 시 앱인스턴스가 삽입되어 있는 것을 알 수 있습니다.그래서 접속할 수 있습니다.this.app.$snotify원하는 장소의 Notify 서비스로 이동합니다.

또한 스토어에서 Nuxt 컨텍스트를 두 번째 인수로 받는 또 다른 장소는nuxtServerInit[2] 즉, 다음 스니펫을 사용하여 서비스에 접속할 수 있습니다.

actions: {
    nuxtServerInit ({ state }, { app }) {
        // Workaround
        state.Snotify = app.$snotify // inject the context in the store
    },
    // Then, you can called as you want
    // There is not necessity to prefix the method with async keyword
    errorHandler ({ state }, message) {
        state.Snotify.error(message)
    }
}

좋아요.

제가 보기에 이 상점은 데이터의 표시 동작을 처리할 책임이 없습니다.따라서 이 경우 스토어의 유일한 목적은 플래시 메시지로 표시되는 컴포넌트 간에 메시지를 전달하는 것입니다.이 경우 Notify를 사용합니다.그 발언에 대한 나의 감상을 결론짓기 위해, 나는 행동만이 정의상 유일한 진실의 원천으로서 가게의 상태를 바꿀 책임이 있다고 생각한다.

대신 변환을 사용하여 개체만 저장해야 합니다.그런 다음 보기 또는 HOC(High Order Component)에서 사용 가능한 위치에 Notify를 사용하여 프레젠테이션 로직을 설정합니다.라이브러리Vuex와 통신하기 위한 API가 뛰어나고 프레젠테이션인터페이스(UI/UX)도 좋기 때문에 이 라이브러리를 적극 추천합니다.면책사항:저는 이것이 Notify보다 낫다고 말하는 것이 아닙니다.각각은 적어도 UX의 컨셉에 관한 한 목적을 약간 다르게 충족시키기 위해 구축되었습니다.둘 다 훌륭하며, 이 사용 사례를 설명하기 위해 어떤 방식으로든 사용할 수 있습니다.


두 번째 스니펫을 다음에 대해 변경합니다.

state: {
    flash: null
}
mutations: {
    // Just extract message from the context that you are set before
    SET_ERROR (state, { message, title = 'Something happens!' }) {
        state.flash = { 
            type: 'error',
            title, 
            message
        }
    },
    FLUSH_FLASH (state) {
        state.flash = null
    }
}

또, 이것을 몇개의 뷰/레이아웃/컴포넌트/HOC에 추가합니다(SFC 방식을 가장 일반적으로 사용했습니다).

<template>
    <vue-snotify />
    ...
</template>

<script>
   export default {
       // I use fetch because this is the lifecycle hook that executes 
       // immediately before page render is sure. And its purpose is to fill
       // the store before page render. But, to the best of my knowledge, 
       // this is the only place that you could use to trigger an immediately
       // executed function at the beginning of page render. However, also
       // you could use a middleware instead or "preferably use a wrapper 
       // component and get leverage of component lifecycle and use `mounted`" [4]
       fetch({ app, store }) {
           if (store.state.flash) {
               const { type, title, message: body } = store.state.flash
               const toast = app.$snotify[type](body, title)

               toast.on('destroyed', (t) => { store.commit('FLUSH_FLASH') })
           }
       },
       data: () => ({
           ...
       })
</script>

위의 코드가 제대로 기능하지 않을 수도 있지만, 유사한 접근 방식을 테스트하여 고객의 요구에 맞는 것을 권장합니다.

편집

컴포넌트 라이프 사이클과 관련된 최신 업데이트를 바탕으로 답변에 또 다른 개선점을 지적하고 싶습니다.처음에 메시지를 컴포넌트 안에 넣으려고 합니다.mounted를 보고 Nuxt가 여전히 Vue라는 것을 알게 될 때까지 Nuxt 페이지는 라이프 사이클이 다르다고 생각했습니다.따라서 어떤 페이지도 정의상 컴포넌트입니다.그러면 의미론적인 접근도 할 수 있습니다.

<template>
    <vue-snotify />
    ...
</template>

<script>
   export default {
       data: () => ({
           ...
       }),
       // Show the flash at the beginning when it's necessary
       mounted: {
           if (this.notification) {
               const { type, title, message: body } = this.notification
               const toast = this.$snotify[type](body, title)

               toast.on('destroyed', (t) => { this.$store.commit('FLUSH_FLASH') })
           }
       },
       computed: {
           notification () {
               return this.$store.state.flush
           }
       }
</script>

레퍼런스

[1] https://zendev.com/2018/06/07/async-data-options-in-vue-nuxt.html

[2] https://twitter.com/krutiepatel/status/1000022559184764930

[3] https://github.com/artemsky/vue-snotify/blob/master/example/src/App/app.ts

[4] https://medium.com/ @ fish percolator / https://medium.com/ - a - global - bar - in - nuxt - substetify - using - vuex - a92b78e5651b

언급URL : https://stackoverflow.com/questions/50215163/vuejs-vuex-and-flash-messages

반응형