[Vue/Nuxt] Vuetify snackbar 를 전역으로 사용하기 > IT 기술백서

IT 기술백서

직접 알아내거나 검색하기 귀찮아서 모아 둔 것

JavaScript | [Vue/Nuxt] Vuetify snackbar 를 전역으로 사용하기

본문

/store/snackbar.js

[code]

export const state = () => ({

  message: '',

  color: '',

})


export const mutations = {

  showMessage(state, payload) {

    state.message = payload.message

    state.color = payload.color || 'primary'

  },

}

[/code]

 

/plugins/snackbar.js

[code]

export default ({ app, store }, inject) => {

  inject('snackbar', {

    showMessage({ message = '', color = '' }) {

      store.commit('snackbar/showMessage', { message, color })

    },

  })

}

[/code]

 

/components/Snackbar.vue

[code]

<template>

  <v-snackbar v-model="show" :color="color" :timeout="timeout">

    {{ message }}

    <template v-slot:action="{ attrs }">

      <v-btn text v-bind="attrs" @click="show = false"> Close </v-btn>

    </template>

  </v-snackbar>

</template>


<script>

export default {

  data() {

    return {

      show: false,

      message: '',

      color: '',

      timeout: 2000,

    }

  },


  created() {

    this.$store.subscribe((mutation, state) => {

      if (mutation.type === 'snackbar/showMessage') {

        this.message = state.snackbar.message

        this.color = state.snackbar.color

        this.show = true

      }

    })

  },

}

</script>

[/code]

store.subscribe()  함수는 mutaion 이 작동할때 후킹이 가능하도록 해주는 함수이다.

 

/nuxt.config.js

[code]

plugins: [

  { src: '~/plugins/snackbar.js', ssr: false },

],

[/code]

 

사용하기

[code]

<template>

  <div>

    <button @click="doTest">클릭</button>

  </div>

</template>

 

<script>

export default {

  methods: {

    doTest() {

      this.$snackbar.showMessage( { message: '스낵바테스트', color: 'info' })

    }

  }

}

</script>

[/code]

댓글 0개

등록된 댓글이 없습니다.

Menu