Github每日精选(第42期):web前端自定义Alert窗口sweetalert

sweetalert

sweetalert 是一个 可以用来替换JavaScript“Alert”的漂亮的控件,用起来简单,而且有丰富的形式,在交互的过程中,用上sweetalert 会使你的交互模式提高一个 档次。

Github每日精选(第42期):web前端自定义Alert窗口sweetalert_第1张图片

github的地址在这里。

安装

NMP

NMP结合Browserify或Webpack等工具是安装 SweetAlert 的推荐方法。

npm install sweetalert --save
CDN

还可以在unpkg和jsDelivr 上找到SweetAlert并使用全局swal变量。

< script src = " https://unpkg.com/sweetalert/dist/sweetalert.min.js " > < / script > 

实例

直接来看看使用的实例,我们就能够清楚的了解sweetalert ,更多的例子可以参看官方实例。

错误提示

swal("Oops!", "Something went wrong!", "error");

Github每日精选(第42期):web前端自定义Alert窗口sweetalert_第2张图片

一条警告消息,带有附加到确认消息的功能:

使用承诺:

swal({
  title: "Are you sure?",
  text: "Are you sure that you want to leave this page?",
  icon: "warning",
  dangerMode: true,
})
.then(willDelete => {
  if (willDelete) {
    swal("Deleted!", "Your imaginary file has been deleted!", "success");
  }
});

Github每日精选(第42期):web前端自定义Alert窗口sweetalert_第3张图片
使用异步/等待:

const willDelete = await swal({
  title: "Are you sure?",
  text: "Are you sure that you want to delete this file?",
  icon: "warning",
  dangerMode: true,
});

if (willDelete) {
  swal("Deleted!", "Your imaginary file has been deleted!", "success");
}

提示模式,其中记录了用户的输入:

使用承诺:

swal("Type something:", {
  content: "input",
})
.then((value) => {
  swal(`You typed: ${value}`);
});

Github每日精选(第42期):web前端自定义Alert窗口sweetalert_第4张图片
使用异步/等待:

const value = await swal("Type something:", {
  content: "input",
});

swal(`You typed: ${value}`);

与 Fetch 结合使用:

使用承诺:

swal({
  text: "Wanna log some information about Bulbasaur?",
  button: {
    text: "Search!",
    closeModal: false,
  },
})
.then(willSearch => {
  if (willSearch) {
    return fetch("http://pokeapi.co/api/v2/pokemon/1");
  }
})
.then(result => result.json())
.then(json => console.log(json))
.catch(err => {
  swal("Oops!", "Seems like we couldn't fetch the info", "error");
});

Github每日精选(第42期):web前端自定义Alert窗口sweetalert_第5张图片
使用异步/等待:

const willSearch = await swal({
  text: "Wanna log some information about Bulbasaur?",
  button: {
    text: "Search!",
    closeModal: false,
  },
});

if (willSearch) {
  try {
    const result = await fetch("http://pokeapi.co/api/v2/pokemon/1");
    const json = await result.json();
    console.log(json);
  } catch (err) {
    swal("Oops!", "Seems like we couldn't fetch the info", "error");
  }
}
React一起使用

如果你正在使用 React,除了主库之外,你还可以使用 React 安装SweetAlert ,并轻松地将React组件添加到警报中,如下所示:

import React from 'react'
import swal from '@sweetalert/with-react'

swal(
  <div>
    <h1>Hello world!</h1>
    <p>
      This is now rendered with JSX!
    </p>
  </div>
)

更多的文档在这里。

你可能感兴趣的:(Github每日精选,前端,github,javascript,Alert)