Vue实战之插件 sweetalert 的使用

安装
npm install sweetalert2@7.15.1 --save

封装 sweetalert
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
}
}

/*
Vue.js 的插件有一个公开方法 install ,这个方法的第一个参数是 Vue 构造器。
将 swal 添加成全局方法和实例的方法后,我们就能通过 Vue.swal 和 this.$swal 进行访问。

注:添加实例方法时,方法名前面的 $ 不是必须的,但我们推荐加上它,以避免和组件定义的属性和方法产生冲突。
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
入口文件引入并使用
// 引入插件
import VueSweetalert2 from './plugins/vue-sweetalert2'

// 使用插件
Vue.use(VueSweetalert2)
1
2
3
4
5
Vue文件中使用插件
logout() {
this.$swal({
text: '你确定要退出吗?',
confirmButtonText: '退出'
}).then((res) => {
if (res.value) {
this.$store.dispatch('logout')
}
})
}
1
2
3
4
5
6
7
8
9
10
延伸
const Message = Vue.extend(MessageComponent)
const vm = new Message()
const $el = vm.$mount().$el
Vue.extend 用来创建一个新『子类』,其参数是一个包含组件选项的对象,对应我们这里的 Message 组件;
使用 new 关键字可以创建一个新的 Message 实例,因为没有指定 el 挂载目标,当前实例处于『未挂载』状态;
使用 vm.$mount() 手动地挂载一个未挂载的实例,并返回当前实例,此时我们能从实例获取 $el

vm.$on('update:show', (value) => {
vm.show = value
})
$on 用来监听当前实例上的自定义事件,其第一个参数是事件名称或包含事件名称的数组,
其第二个参数是回调函数,该函数会接收触发函数的所有参数
---------------------

posted @ 2019-06-08 00:35  水至清明  阅读(2140)  评论(0编辑  收藏  举报