时间:2021-07-01 10:21:17 帮助过:143人阅读
npm install sweetalert2@7.15.1 --save
在 src 新建 plugins 文件夹,然后新建 vue-sweetalert2.js 文件,复制贴入以下代码:
src/plugins/vue-sweetalert2.js
import swal from 'sweetalert2'
export default {
install: (Vue) => {
// sweetalert2 的设置默认配置的方法
swal.setDefaults({
type: 'warning',
showCancelButton: true,
confirmButtonColor: 'rgb(140,212,245)',
cancelButtonColor: 'rgb(193,193,193)'
})
// 添加全局方法
Vue.swal = swal
// 添加实例方法
Vue.prototype.$swal = swal
}
}我们这里将 sweetalert2 封装成一个插件,Vue.js 的插件有一个公开方法 install ,这个方法的第一个参数是 Vue 构造器。将 swal 添加成全局方法和实例的方法后,我们就能通过 Vue.swal 和 this.$swal 进行访问
打开 src/main.js 文件,引入并使用 ./plugins/vue-sweetalert2(单行注释部分是涉及的修改):
src/main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import './directives'
import './components'
import store from './store'
// 引入插件
import VueSweetalert2 from './plugins/vue-sweetalert2'
// 使用插件
Vue.use(VueSweetalert2)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})打开 src/components/layouts/TheEntry.vue 文件,修改 logout 方法:
src/components/layouts/TheEntry.vue
logout() {
this.$swal({
text: '你确定要退出吗?',
confirmButtonText: '退出'
}).then((res) => {
if (res.value) {
this.$store.dispatch('logout')
}
})
}相关推荐:
vue中Element表单验证的使用方法
layer弹窗插件的使用教程
以上就是在vue项目中如何使用sweetalert2弹窗插件的详细内容,更多请关注Gxl网其它相关文章!