使用 vue-snotify 在 Vue.js 中发布通知

我总是害怕在我写的每一个应用程序中实施一些东西. 模特对话(很难在移动设备上得到正确的)和吐槽 / 通知 / 警告 / 任何东西. 不是本地移动 / 桌面推送通知,这些都是相对容易的。 吐槽的困难是在构建一个足够灵活的系统来处理多个通知,正在进行的操作,各种风格,各种类型的内容,同时保持出色的动画来显示和隐藏。

安装

在 Vue.js 项目中安装 vue-snotify。

1# Yarn
2$ yarn add vue-snotify
3# NPM
4$ npm install vue-snotify --save

使用

现在在主Vue设置文件中启用插件。

 1[label main.js]
 2import Vue from 'vue';
 3import App from './App.vue';
 4import Snotify from 'vue-snotify';
 5// You also need to import the styles. If you're using webpack's css-loader, you can do so here:
 6import 'vue-snotify/styles/material.css'; // or dark.css or simple.css
 7
 8Vue.use(Snotify);
 9
10new Vue({
11  el: '#app',
12  render: h => h(App)
13});

现在,在您的主要应用程序元素中添加vue-snotify组件,这就是通知的结果。

1[label App.vue]
2<template>
3  <div id="app">
4    <!-- Your app stuff here -->
5    <vue-snotify></vue-snotify>
6  </div>
7</template>

从那里,您可以开始使用Snotify与注入的vm.$snotify对象。

所有通知都可以用 这些属性配置。

简单

相当无聊的传统传统普通(我在这里说话)通知。

 1...
 2export default {
 3  methods: {
 4    displayNotification() {
 5      this.$snotify.simple({
 6        body: 'My Notification Body'
 7        title: 'Notification Title',
 8        config: {}
 9      });
10    }
11  }
12}

成功 / 信息 / 警告 / 错误

所有这些都以各自的颜色显示一个简单的通知。

• 成功*

 1...
 2export default {
 3  methods: {
 4    displayNotification() {
 5      this.$snotify.success({
 6        body: 'Success Body'
 7        title: 'Success Title',
 8        config: {}
 9      });
10    }
11  }
12}
  • 错误 *
 1...
 2export default {
 3  methods: {
 4    displayNotification() {
 5      this.$snotify.error({
 6        body: 'Error Body'
 7        title: 'Error Title',
 8        config: {}
 9      });
10    }
11  }
12}

警告( )

 1...
 2export default {
 3  methods: {
 4    displayNotification() {
 5      this.$snotify.warning({
 6        body: 'Warning Body'
 7        title: 'Warning Title',
 8        config: {}
 9      });
10    }
11  }
12}

【信息】

 1...
 2export default {
 3  methods: {
 4    displayNotification() {
 5      this.$snotify.info({
 6        body: 'Info Body'
 7        title: 'Info Title',
 8        config: {}
 9      });
10    }
11  }
12}

非同步通知

Snotify 有一个内置的系统,用于非同步通知,尽管它们可能有点难理解。

 1...
 2displayNotification() {
 3  this.$snotify.async({
 4    body: 'Working on a thing...'
 5    title: 'Working',
 6    config: {},
 7
 8    action: () => new Promise((resolve, reject) => {
 9      // Do async stuff here.
10      setTimeout(() => {
11        resolve(); // Success
12        /*  reject(); // Error
13            // Custom replacement.
14            resolve({
15              body: 'Custom Success',
16              config: {}
17            })
18        */
19      }, 2000);
20    })
21  });
22}

因此,基本上,async 通知应该具有一个行动属性,这是一个返回承诺的函数. 如果承诺得到解决,则 async 通知被替换为成功通知.如果被拒绝,则被替换为错误。

其他

有几种其他通知类型,允许用户互动,如 confirm, prompthtml通知。

还有一个很棒的小游乐场可以测试各种可用的选项(https://artemsky.github.io/vue-snotify/)。

Published At
Categories with 技术
Tagged with
comments powered by Disqus