Tips for making a versatile Vuetify Snackbar that can be used multiple times

I am in the process of developing a reusable alert/snackbar component. My implementation looks like this:

Snackbar.vue

<template>
    <v-snackbar transition="true" timeout="2000" :show="`${show}`" :color="`${color}`" absolute top outlined right>
        <strong>
            {{ message }}
        </strong>
    </v-snackbar>
</template>

<script>
export default {
    name: 'Snackbar',
    props: {
        show: String,
        color: String,
        message: String
    }
}
</script>
<template>
    <v-snackbar transition="true" timeout="2000" :show="`${show}`" :color="`${color}`" absolute top outlined right>
        <strong>
            {{ message }}
        </strong>
    </v-snackbar>
</template>

<script>
export default {
    name: 'Snackbar',
    props: {
        show: String,
        color: String,
        message: String
    }
}
</script>

I have imported the component and passed props to it like this:

import Snackbar from '../../../components/Snackbar'

<Snackbar v-if="alert" color="alertColor" message="alertMessage" />
<Snackbar show="alert" color="alertColor" message="alertMessage" />

I have tested the 2 lines above, and these are the values of those 3 variables

  • alert = true
  • alertColor = green
  • alertMessage =
    create.vue?f4fe:631 DB error - insert_marketing_campaign: Duplicate entry 'TEST' for key 'MARKETING_CAMPAIGN_AK'

Outcome

I am not seeing any errors in the console, but the snackbar is not appearing either. Please assist

Answer №1

Factorial of 8!

Your method of passing props values needs adjustment, you should follow this approach:

By the way, I included an event listener(update) for demonstration purposes to handle a close button(remove if not needed)

<Snackbar :show="alert" :color="alertColor" :message="alertMessage" v-on:update="alert = $event" />

Snackbar.vue

I made some changes in this file as well:

  • The way you are using props in the attributes is fine, but if you don't require concatenation with other values, keep it simple
  • The prop show should be a Boolean
  • Added a stylish button in case you wish to use it
  • v-model controls the visibility of the snackbar, however, you cannot directly use the prop show with v-model, which is why we have a computed property "show2"(quite imaginative) that reads(get) the value of the prop show and emits a custom event "update" if you intend to modify it(set)
<template>
    <v-snackbar transition="true" timeout="2000" v-model="show2" :color="color" absolute top outlined right>
        <strong>
            {{ message }}
        </strong>
        <v-btn color="red" text @click="show2 = false">Close</v-btn>
    </v-snackbar>
</template>
<script>
export default {
  props: {
    show: Boolean,
    color: String,
    message: String,
  },
  computed: {
    show2: {
      get() {
        return this.show;
      },
      set(value) {
        this.$emit("update", value);
      },
    },
  },
};
</script>

Trust this information is beneficial! ;)

Answer №2

Take a look at this sandbox I created for you: https://codesandbox.io/s/stack-71244492-vuex-snackbar-klfunf?file=/src/store/index.js

To set up a global snackbar in your App.vue file and update it with Vuex, you need to define a snackbar object in your Vuex store and implement a simple update mutation as well as a show action.

// store/index.js
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    snackbar: { active: false, color: "", message: "", timer: 4000 }
  },
  mutations: {
    UPDATE_SNACKBAR(state, snackbar) {
      state.snackbar = snackbar;
    }
  },
  actions: {
    showSnack({ commit }, { message, color, timer }) {
      commit("UPDATE_SNACKBAR", {
        active: true,
        color: color,
        message: message,
        timer: timer
      });
    }
  }
});

Then, in your App.vue, you can configure it as follows

<v-snackbar
   v-model="snackbar.active"
   :color="snackbar.color"
   :right="true"
   :bottom="true"
   :timeout="snackbar.timer"
>
   {{ snackbar.message }}
   <template #action="{ attrs }">
      <v-btn
         color="white"
         text
         v-bind="attrs"
         @click="snackbar.active = false"
      >
         Close
      </v-btn>
   </template>
</v-snackbar>
<script>
import { mapState } from "vuex";
export default {
   name: 'App',
   data: () => ({
      drawer: false,
   }),
   computed: {        
    ...mapState(["snackbar"])    
   }
}
</script>

Once set up, you can trigger the snackbar from any component by simply executing the following code

// views/Home.vue
this.$store.dispatch('showSnack', {
   message: 'Testing, main page.',
   color: 'green darken-1'
})

// views/About.vue
this.$store.dispatch('showSnack', {
   message: 'Hello from about!',
   color: 'red darken-1',
   timer: 2000
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to increase the row spacing in an Ant Design Table?

I have a table with expandable rows in antd, and I am looking to add some vertical space between the rows. I've tried using the rowClassName property provided by antd, but it did not work as expected. I also attempted to use a custom component, but th ...

What is the best way to include basic static files and HTML together in a NodeJS environment?

I am facing an issue trying to serve an HTML file with its CSS and JS files in NodeJS using express.static(), but unfortunately, it is not working as expected. I have followed the steps shown in several tutorials, but for some reason, the output is not co ...

Encountered a header error while attempting to proceed with the

In one of my routes, the following code is implemented: if (elements.length <= 0) { var msg = 'no elements found'; console.error(msg); var err = new Error('Not found'); ...

Error: export keyword used incorrectly

Currently, I am in the process of developing an npm package called foobar locally. This allows me to make real-time changes and modifications without the need to constantly publish and unpublish the package, which greatly improves my development efficiency ...

Transform the Vue.js component into a Webpack component

I found this code in a tutorial and now I need to make some modifications so it can be compiled with Webpack, including the template script and CSS files. <html> <head> <title>VueJs Instance</title> <s ...

Tracking in node.js to detect the creation of a new file

I'm currently working on a node.js script that requires immediate action upon the creation of a file with a specific name in a designated directory. While one way to achieve this could be through continuous calls to fs.readdir until the desired file i ...

Having a minor problem in attempting to retrieve a random value

Having trouble generating a random number from a function. Can someone help explain? const MyButton = document.querySelector(".Flipper"); MyButton.addEventListener("click", recordLog); function recordLog (){ MyButton.style.backgr ...

Implement dynamic message based on user interaction using v-on:click in Vue

I am trying to show my IP address when a button is clicked in Vue. Check out my code below: <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3244475772001c071c0305">[email pr ...

Different ways to incorporate a property within fabric items

When I attempt to add the editable attribute to an image object in fabric and then use console.log(canvas.toJSON()), the editable attribute does not show up in the object. This is how my code looks: const image = 'https//www.test.com/test.png' f ...

Is there a way to handle an error or display N/A when an object is not found in the JSON data I am working with?

Today's games lineup and broadcasting channels can be displayed using this JSON format. However, I am encountering the following error: TypeError: /home/ubuntu/workspace/sportsapp/views/results.ejs:8 6| <% data["games"].forEach(function(game){ ...

Developing web applications using a combination of PHP, MySQL, and

I am in need of creating an HTML form that functions as CRUD. This form should be able to record inputs such as "row_number", "channel_name", and "ip_address". It will store all the data in a MySQL table using the "ORDER BY row_number" function. The form i ...

Exploring the World of JSON Nested Arrays with Unknown Titles and Organizing Them for Storage

Apologies if this question has already been addressed elsewhere, but I couldn't find it. I have a JSON object with dynamic keys: { "main": [ { "Example1": [ { "Example1_Var02": "5", ...

Tips for providing support to a website without an internet connection

I am in the process of creating a sales platform for a grocery store that utilizes PHP/MySQL. I have come across some websites that are able to fully reload and function even without internet access. For instance, when I initially visited abc.com, everyth ...

Is there a way to automatically refresh a webpage whenever there are changes

Currently, I have a webpage that operates like a reverse auction, complete with a javascript countdown timer that tracks the time remaining in the auction. Once the timer reaches zero, the auction ends and the page automatically refreshes. While everythin ...

Emulating an Ajax request

I am struggling with incorporating a button that has three states - initial, loading, and success/failure - into my code. Specifically, I want the button to display a "tick" symbol and a success message after a timed-out ajax call. The HTML code below sho ...

How big should the placeholder image be for the image area?

How can I create a loading image to replace a .gif while it loads? I need a placeholder image of about 325x325 (same size as the gif) to keep content in place. I've attempted using background: url() without success and haven't explored JS/jQuery ...

Send a PUT request using Ajax

I am a beginner when it comes to Ajax requests and I have crafted the code shared in this Pastie. On line 107, my $.PUT function is causing an error in Firebug stating that $.PUT is not a recognized function. I acknowledge that there are issues with my aja ...

How can I switch the data source in JavaScript when a dropdown is clicked?

I have a webpage designed with HTML that features a dropdown menu and a div element intended to showcase a map: <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.boot ...

Using JQuery to enable checkbox if another is selected

I have a single checkbox that reveals a hidden div when checked. Inside this div, there are two additional checkboxes. My goal is to disable the initial checkbox if either of these two checkboxes is checked. Here's the HTML code snippet: <p> ...

Exploring the power of Angular JS promises through ng-repeat

My current project involves fetching latitude and longitude coordinates from a postcode using an API, then utilizing those coordinates to retrieve data on street level crimes near that location on a specific date through the UK police API. However, I have ...