GithubHelp home page GithubHelp logo

keen-on-design / vue-flash-message Goto Github PK

View Code? Open in Web Editor NEW
89.0 4.0 20.0 665 KB

Vue js flash messages component

License: MIT License

JavaScript 71.01% Vue 16.41% HTML 9.40% CSS 3.18%
vuejs flash-messages notifications javascript

vue-flash-message's Introduction

vue-flash-message

npm NpmLicense Awesome

Simple yet flexible vue flash alert message component. It is made to display a list of messages and give individual control over each instance and global message storage. Component is inspired by old goodies as jGrowl.

Buy Me A Coffee

Demo & Example

Install

  npm install --save vue-flash-message

Configuration

import Vue from 'vue';
import VueFlashMessage from 'vue-flash-message';
Vue.use(VueFlashMessage);

You can rename default flash method via options:

Vue.use(VueFlashMessage, { method: 'iPreferQuickSilver' });

Usage

Output flash message pool and configure transitions.

<flash-message class="myCustomClass"></flash-message>

(Optional) Include pre defined basic css.

require('vue-flash-message/dist/vue-flash-message.min.css');

Emit flash messages from any component with a flash (or custom named) method.

this.flash('Data loaded', 'success');
this.flash('Validation failed', 'error');
this.flash('Spawning too much alerts is a bad UX', 'warning');
this.flash('Live long and prosper', 'info');

Shortcut methods

You can also use shortcut methods to output common message types

this.flashSuccess('Data loaded');
this.flashError('Validation failed');
this.flashWarning('Spawning too much alerts is a bad UX');
this.flashInfo('Live long and prosper');

You if you don't want to spoil your components with these methods, you can switch them off by using createShortcuts config option.

Vue.use(VueFlashMessage, {
  createShortcuts: false,
});

Usage with options

this.flash('Hello World', 'success', {
  timeout: 3000,
  beforeDestroy() {
    alert('oh no, not again!');
  }
});

Options

Name Type Default Desciption
timeout Number 0 Number in milliseconds until message self destruct
important Boolean false Defines if message has a close button.
autoEmit Boolean true Defines if message should be emitted immediately after calling flash method
pauseOnInteract Boolean false Defines if message destruct timer should be paused on user interaction
beforeDestroy Function - Fires bofore message is destroyed
onStartInteract Function - Fires on user interact with message element
onCompleteInteract Function - Fires on user complete interaction with message element

Props

Name Type Default Desciption
transitionName String custom-classes-transition vue transitions name
outerClass String 'flash__wrapper' outer class name

Passing global message options

Vue.use(VueFlashMessage, {
  messageOptions: {
    timeout: 1000,
    important: true,
    autoEmit: false,
    pauseOnInteract: true
  }
});

API

Flash method returns message object giving you full controll over it's contents, options and lifecycle.

const myMessage = this.flash('My message', 'info');
Method Desciption
emit() Adds message to global storage. Helpfull when message is created with autoEmit: false
destroy() Destroys message
getStorage() Returns global flash message storage object
setSelfDestructTimeout(timeout) Sets message self destruct timer value (in milliseconds)
startSelfDestructTimer() Starts self destruct timer
killSelfDestructTimer() Stops self destruct timer

Calling flash method with no arguments will return flash storage object.

const messageStorage = this.flash();
Method Desciption
flash(...) Same as this.flash method, except it does not return storage instance
push(id, message) Adds message object to storage with id key
destroy(id) Destroys message by given id
destroyAll() Destroys all messages

Vuex usage

You can access flash message storage object directly from Vue prototype:

Vue.prototype.$flashStorage.flash(...);

License

Vue-Flash-Message is open-sourced software licensed under the MIT license.

vue-flash-message's People

Contributors

iohansson avatar keen-on-design avatar pandasensey avatar stevenbuehner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

vue-flash-message's Issues

Precompile default template to remove dependency on runtime compiler

By providing the default template as a string, it is not precompiled even when only the default template is used. You need to include the runtime compile in your vue app just for the plugin.

Why not precompile the default template? E.g. make a .vue component with the default template that can be precompiled (by the app including it) and only use a dynamic string template when explicitly needed.

What do you think?

Is there a way to insert a router link to the message?

I tried

this.info('Please go to <router-link to="/">here</router-link>')

But it doesn't work for obvious reason that it's not going to be compiled. It can work using Dynamic Component, but it requires a change in the implementation. Is there a way to make this happen without having to change the source code?

If not, should this become a feature? I'm happy to try to get it working and create a PR.

Thanks,

TypeError: this.flash is not a function

Hi,
I try to use vue-flash-message in my Vue.js project but I face with TypeError: this.flash is not a function error.

I have registered plugin using:
main.js:

import Vue from 'vue'
import VueFlashMessage from 'vue-flash-message';
Vue.use(VueFlashMessage);
...

And used methods like:
myComponent.vue:

<template>
    <flash-message transitionName="flash" class="flashpool"></flash-message>
    <div @click="doSomething">hello</div>
</template>
<script>
    export default {
        name: 'something',
        data() {
            return {
                ...
            }
        },
        methods: {
            doSomething() {
                this.success('Your password has been updated.'); // TypeError: this.flash is not a function
                this.flash('Your password has been updated.', 'success'); // Again, TypeError: this.flash is not a function
            }
        }
    }
</script>

I also tried to rename default flash method and disabling shortcut creation; not working at all.
I think problem is with registering methods. How should I fix it?

vue: 2.5.16
vue-flash-message: 0.6.0

Template support

Template support

First of all, thanks for creating this plugin. I am web designer for Open Law Library. We have selected to use it with our project since it proved to be best for our needs, especially because it had the possibility for custom templates and styles. With a bit of customization, we were able to achieve something like this

oll-messages

Our template

Our template looked like this one:

const defaultTemplate = `
<transition-group
	:name="transitionName"
	:class="outerClass"
	tag="div"
>
	<div
		v-for="(message, index) in storage"
		:key="index"
		:class="cssClasses(index) + ' flash-message'"
		:aria-labelledby="'flash_' + index"
		tabindex="0"
		role="alert"
		aria-live="polite"
		aria-atomic="true"
		@mouseover="onMouseOver(index)"
		@mouseleave="onMouseOut(index)"
		@keypress.enter="destroyFlash(index)"
		@keypress.space="destroyFlash(index)"
	>
		<div class="flash-message__icon">
			<span v-if="cssClasses(index) === 'info'" class="icon icon-info" aria-label="Information icon"></span>
			<span v-else-if="cssClasses(index) === 'success'" class="icon icon-ok-o" aria-label="Success icon"></span>
			<span v-else-if="cssClasses(index) === 'warning'" class="icon icon-exclamation" aria-label="Warning icon"></span>
			<span v-else-if="cssClasses(index) === 'error'" class="icon icon-exclamation-triangle" aria-label="Error icon"></span>
			<span v-else class="icon icon-oll"></span>
		</div>
		<div :id="'flash_' + index" class="flash-message__content" v-html="message.content"></div>
		<div class="flash-message__close">
			<button v-if="!message.options.important"
				type="button"
				class="button button--icon button--transparent"
				data-dismiss="alert"
				aria-label="Close message"
				@click.stop.prevent="destroyFlash(index)"
			>
				<span class="icon icon-x" aria-label="Close dialog"></span>
			</button>
		</div>
	</div>
</transition-group>
`;

Styles and icons were custom made and were included in the main SCSS file.

Is it possible to create separate .vue component with message template, scripts and styles, which can be reused every time messages are called? I guess that templating would be much easier in this way.

vuex call

How can I show flash-message from vuex action?

Including css require postcss-import because of .postcssrc.js

When I try to include the basic styles (vue-flash-message/dist/vue-flash-message.min.css) it complains that it cannot find postcss-import and I should install it. I traced it down to the .postcssrc.js under node_modules/vue-flash-message/.postcssrc.js โ€“ it seems by importing the styles postcss traverses up until it finds a config and tries to use this.

It should of course only use my own postcss config. I think you should exclude the postcss config from bundling, since it should not be needed when using this as a plugin.

Messages appear at top of page not top of screen

My flash messages are appearing Absolute to the top of the page, so they are hidden if the page is scrolled, these should appear absolute to top of Screen so that they always display.

Is there a way to make these 'fixed' ? Have I missed a setting somewhere?

UPDATE: yes I have, I can now see that I have control over the class where it is inserted in the template, so this issue can be closed. thnx

My first Vue.js Project :)

Hello guys,

please forgive me if i do something wrong but it is my first cone in Vue.js

app.js
`
/**

  • First we will load all of this project's JavaScript dependencies which
  • includes Vue and other libraries. It is a great starting point when
  • building robust, powerful web applications using Vue and Laravel.
    */

require('./bootstrap');

window.Vue = require('vue');

/**

  • Next, we will create a fresh Vue application instance and attach it to
  • the page. Then, you may begin adding components to this application
  • or customize the JavaScript scaffolding to fit your unique needs.
    */

//Vue.component('example-component', require('./components/ExampleComponent.vue'));

import VueFlashMessage from 'vue-flash-message';
Vue.use(VueFlashMessage);
require('vue-flash-message/dist/vue-flash-message.min.css');

Vue.component('comments',require('./components/Comments'));
Vue.component('navbar',require('./components/Navbar'));

const app = new Vue({
el: '#app',
});
`

Comments.vue file - part of it

 export default {
        name: "Comments",
        data() {
            return {
                comments: [],
                login: true,
                comment: {
                    id: '',
                    body: '',
                    user_id: '',
                    avatar: '',
                    user: '',
                    created_at: '',
                    parent_id: '',
                    module_id: ''
                },
                comment_id: '',
                pagination: {},
                edit: false
            }
        },
        created() {
            this.flash('Data loaded', 'success');
            this.flash('Validation failed', 'error');
            this.flash('Spawning too much alerts is a bad UX', 'warning');
            this.flash('Live long and prosper', 'info');
            this.fetchComments();
            this.randomNumber();
        },
        methods: {
            fetchComments(page_url) {
                let vm = this;
                page_url = page_url || '/api/1/1/',
                    fetch(page_url)
                        .then(res => res.json()
                        )
                        .then(res => {
                            this.comments = res.data;
                            vm.makePagination(res.meta, res.links);
                        })
                        .catch(err => console.log(err)
                        );
                this.flash('Hello World', 'success', {
                    timeout: 3000,
                    beforeDestroy() {
                        alert('oh no, not again!');
                    }
                });
            },
            makePagination(meta, links) {
                let pagination = {
                    current_page: meta.current_page,
                    last_page: meta.last_page,
                    next_page_url: links.next,
                    prev_page_url: links.prev

                }
                this.pagination = pagination;
            },
            addComment() {

                fetch('/api', {
                    method: 'post',
                    body: JSON.stringify(this.comment),
                    headers: {
                        'content-type': 'application/json'
                    }
                })
                    .then(res => res.json())
                    .then(data => {
                        this.comment.body = '';
                        this.fetchComments();
                        alert('added');
                    })
                    .catch(err => console.log(err));

            },
            deleteComment(id) {
                fetch(`/api/comment/${id}`, {
                    method: 'delete'
                }).then(res => res.json())
                    .then(
                        this.fetchComments()
                    )
                    .catch(err => console.log(err))
            },
            randomNumber: function () {
                this.random = Math.floor(Math.random() * (10 - 1 + 1)) + 1
            }
        }
    }

in same file i have my <template></template> and now where i have to put <flash-message class="myCustomClass"></flash-message> ?

i don'` get any errors, all files are compiled. however i see alert message not flash messages.

Any ideas why ?

Shortcuts: Name conflict with vue 2.5.17

With maybe the latest release of vue 2.5.17 there seems to be some conflicts due to the shortcuts named 'success' and 'error' โ€“ same as the methods in vue.
Vue thows these errors for each v-input:

[Vue warn]: Method "success" has already been defined as a prop.
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "success"

Only way around seems to be to set createShortcuts: false in main.js which works as expected:

Vue.use(VueFlashMessage,
  {
    messageOptions: {
      timeout: 3000,
      ...
    },
    template,
    createShortcuts: false  }
);

Thanks!

Cannot read property 'destroy' of undefined

ui.click | button.flash__close-button[type="button"] > span

exception | TypeError: Cannot read property 'destroy' of undefined

{snip} this.storage[e]},destroyFlash:function(e){this.getFlash(e).destroy()},onMouseOver:function(e){var t=this.getFlash(e);void 0!==t&&t.onStartI {snip}

Vuex usage and passing global message options

When I call function flash() from Vuex it works but it doesn't apply global options like

Vue.use(VueFlashMessage, {
  messageOptions: {
    timeout: 1000,
  }
});

Calling it from Vuex does also support passing global options?

Only one message at a time

Is it possible to show only one message at a time? Or maybe to invalidate previous messages when spawning a new one? Thanks!

Runtime Error: You are using the runtime-only build of Vue where the template compiler is not available.

Hi,
I'm getting the following error in chrome when I try to use the vue-flash-message:

main.ts:23 [Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

found in

--->
at src\App.vue

I'm running the project in development mode with the vue-cli. It's a brand new project. I'm using Typescript.

Here are few relevant code snippets.
main.ts
import Vue from 'vue'
import VueFlashMessage from 'vue-flash-message';
Vue.use(VueFlashMessage);

App.vue

I'm pretty sure I need to use a different version of Vue than what I'm including via import Vue from 'vue' but I can't figure out how to make things work.

z-index

The default value of the style z-index of the block is too small for such a popup

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.