可能你注意到在一些網站上有下面這個特別酷炫的彈出框,用戶體驗來講感受頗有層次動態感,比靜態的模態彈出框/消息提示更能吸引人注意,給人一種醒目,很酷的感受!css
這裏使用的就是SweetAlert2庫。html
SweetAlert2是SweetAlert-js的升級版本,它解決了SweetAlert-js中不能嵌入HTML標籤的問題,並對彈出對話框進行了優化,同時提供對各類表單元素的支持,還增長了5種情景模式的模態對話框,支持響應式佈局。如今還支持toast消息提示框,輸入表單驗證等。它是jsDelivr排名上第23名的最受歡迎的包。vue
能夠經過yarn或npm來安裝sweetalert2對話框插件。git
npm install --save sweetalert2 yarn add sweetalert2
html直接引入方式:es6
<script src="sweetalert2.all.min.js"></script> <!-- Optional: include a polyfill for ES6 Promises for IE11 --> <script src="https://cdn.jsdelivr.net/npm/promise-polyfill"></script> <script src="sweetalert2.min.js"></script> <link rel="stylesheet" href="sweetalert2.min.css">
採用es6方式引入使用:github
import Swal from 'sweetalert2/dist/sweetalert2.js' import 'sweetalert2/src/sweetalert2.scss' // ES6 Modules or TypeScript import Swal from 'sweetalert2' // CommonJS const Swal = require('sweetalert2')
而後直接輸入如下代碼便可看到上圖的效果:vue-cli
Swal.fire({ title: 'Good Job!', text: 'Keep moving forward', icon: 'success', confirmButtonText: 'Ok' })
已經有現成的輪子寫好了對應的vue版的sweetalert2 ,名稱爲: vue-sweetalert2. 可搜索查看該包相詳細使用說明。這裏簡單介紹下經常使用用法。npm
// vue-cli使用方法 // main.js import Vue from 'vue'; import VueSweetalert2 from 'vue-sweetalert2'; const options = { confirmButtonColor: '#41b882', cancelButtonColor: '#ff7674', }; Vue.use(VueSweetalert2, options); // vue-nuxt使用方法 // 1. npm包導入 "vue-sweetalert2": "^3.0.6", // 2. nuxt.config.js中引入默認配置 modules: [ [ 'vue-sweetalert2/nuxt', { confirmButtonColor: '#41b882', cancelButtonColor: '#ff7674' } ] ]
注意: 在nuxt集成中,默認的this.$swal引入的是 sweetalert2的 swal.fire方法,而非swal實例。promise
// 寫法一 this.$swal('成功', '成績獲取成功!', 'success') // 寫法二 this.$swal({ icon: 'success', text: '最新數據更新成功!', confirmButtonText: '好的' }) 2. 彈出一個消息提示,不是彈出框 this.$swal({ icon: 'success', position: 'top-right', toast: true, timer: 3000, timerProgressBar: true, title: '數據更新完成!', showConfirmButton: false, allowOutsideClick: true, allowEscapeKey: true, onOpen: (toast) => { toast.addEventListener('mouseenter', Swal.stopTimer) toast.addEventListener('mouseleave', Swal.resumeTimer) } })
this.$swal({}).then((res) => { console.log(res) }) // 對應的res返回的是一個對象,包含以下信息: dismiss: "timer" isConfirmed: false isDismissed: true value: '' ``` 能夠經過以上屬性獲取彈出框消失類型或者是不是關閉或者確認按鈕響應的。其中dismiss是個字符串來表明 關閉的類型: module:sweetalert2.Swal.DismissReason 可選值爲: cancel, backdrop, close, esc, timer ## 4. 圖標自定義 ``` ({ title:'成功登陸!', showCancelButton: false, closeOnConfirm: false, imageUrl: 'https://unsplash.it/400/200', imageWidth: 200, imageHeight: 200, animation: false }) ``` 還有更多其餘好玩的用法,能夠到倉庫中查看相關詳細文檔。 中文文檔: http://mishengqiang.com/sweetalert2/ 英文文檔: https://sweetalert2.github.i