vue使用sweetalert2弹窗插件

1). 安装 sweetalert2

npm install [email protected] --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 }

猜你喜欢

转载自www.cnblogs.com/yangguoe/p/9316624.html
今日推荐