9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Nuxt.js + Vuetify】フラッシュメッセージ表示機能実装

Last updated at Posted at 2021-03-21

概要

ポートフォリオ作成の為、nuxt.js+Vuetifyでフラッシュメッセージ
(vuexとvuetifyのsnackbarを使用)
の表示機能を作成したので備忘録までに残します。

完成物

右上にフェードしながらsnackbarが表示される
(下記参考動画は作成したポートフォリオ上での挙動)
flashmessage.gif

コード

フラシュメッセージ表示用

/components/FlashMessage.vue
<template>
  <v-snackbar
    v-model="status"
    transition="slide-x-reverse-transition"
    right
    top
    :color="type"
  >
    <div class="ml-5 font-weight-bold white--text">
      {{ message }}
    </div>
  </v-snackbar>
</template>

<script>
import { mapGetters } from "vuex"
export default {
  computed: {
    ...mapGetters({
      message: "flashMessage/message",
      type: "flashMessage/type",
      status: "flashMessage/status",
    }),
  },
}
</script>
/store/flashMessage.js
export const state = () => ({
  message: "",
  type: "",
  status: false,
})

export const getters = {
  message: (state) => state.message,
  type: (state) => state.type,
  status: (state) => state.status,
}

export const mutations = {
  setMessage(state, message) {
    state.message = message
  },
  setType(state, type) {
    state.type = type
  },
  setStatus(state, bool) {
    state.status = bool
  },
}

export const actions = {
  showMessage({ commit }, { message, type, status }) {
    commit("setMessage", message)
    commit("setType", type)
    commit("setStatus", status)
    setTimeout(() => {
      commit("setStatus", !status)
    }, 1000)
  },
}

コンポーネント側で表示する場合

/components/login.vue
<script>
export default {
  methods: {
  /* 表示したい処理中に以下を記述 */
    this.$store.dispatch(
      "flashMessage/showMessage",
      {
        message: "ログインしました.",
        type: "sucess",
        status: true,
      },
      { root: true }
    )
  },
}
</script>

別vuexストアで表示する場合

/store/login.js
export const actions = {
  login({ dispatch }, payload) {
    /* 表示したい処理中に以下を記述 */
    dispatch(
      "flashMessage/showMessage",
      {
        message: "ログインしました.",
        type: "sucess",
        status: true,
      },
      { root: true }
    )
  },
}

messageには表示したいメッセージを記述。
typeにはvuetifyのcolorを記述して好きな色で表示が可能。

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?