1). 安裝 sweetalert2
npm install sweetalert2@7.15.1 --save
2). 封裝 sweetalert2
在 src
新建 plugins
文件夾,然后新建 vue-sweetalert2.js
文件,復制貼入以下代碼:
src/plugins/vue-sweetalert2.js
1 import swal from 'sweetalert2' 2 3 export default { 4 install: (Vue) => { 5 // sweetalert2 的設置默認配置的方法 6 swal.setDefaults({ 7 type: 'warning', 8 showCancelButton: true, 9 confirmButtonColor: 'rgb(140,212,245)', 10 cancelButtonColor: 'rgb(193,193,193)' 11 }) 12 13 // 添加全局方法 14 Vue.swal = swal 15 // 添加實例方法 16 Vue.prototype.$swal = swal 17 } 18 }
我們這里將 sweetalert2 封裝成一個插件,Vue.js 的插件有一個公開方法 install
,這個方法的第一個參數是 Vue 構造器。將 swal
添加成全局方法和實例的方法后,我們就能通過 Vue.swal
和 this.$swal
進行訪問
3). 引入並使用插件
打開 src/main.js
文件,引入並使用 ./plugins/vue-sweetalert2
(單行注釋部分是涉及的修改):
src/main.js
1 import Vue from 'vue' 2 import App from './App' 3 import router from './router' 4 import './directives' 5 import './components' 6 import store from './store' 7 // 引入插件 8 import VueSweetalert2 from './plugins/vue-sweetalert2' 9 10 // 使用插件 11 Vue.use(VueSweetalert2) 12 13 Vue.config.productionTip = false 14 15 /* eslint-disable no-new */ 16 new Vue({ 17 el: '#app', 18 router, 19 store, 20 components: { App }, 21 template: '<App/>' 22 })
4). 添加退出確認
打開 src/components/layouts/TheEntry.vue
文件,修改 logout
方法:
src/components/layouts/TheEntry.vue
1 logout() { 2 this.$swal({ 3 text: '你確定要退出嗎?', 4 confirmButtonText: '退出' 5 }).then((res) => { 6 if (res.value) { 7 this.$store.dispatch('logout') 8 } 9 }) 10 }