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 用來監聽當前實例上的自定義事件,其第一個參數是事件名稱或包含事件名稱的數組,
其第二個參數是回調函數,該函數會接收觸發函數的所有參數
---------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM