Vue自定義全域性彈窗元件
阿新 • • 發佈:2020-08-13
前言
頁面中會有很多時候需要彈窗提示,我們可以寫一個彈窗元件,但是如果每個頁面都引入這個元件,太麻煩了,所以我們將它變成全域性元件,需要用的時候直接通過JS呼叫即可,不需要在每個頁面引入了
效果圖
彈窗元件
在components目錄下新建popup資料夾,然後在裡面建立index.vue檔案和index.js檔案
彈窗的元件——index.vue
<template> <transition-group name='fade'> <!-- 蒙版 --> <div class="mask" key="1" @click="show = false" v-if="show" @touchmove.prevent> </div> <div class="pop" v-show="show" key="2"> <img :src="imgUrl" :alt="imgLoadTip"> <h1>{{title}}</h1> <p>{{content}}</p> <button @click="btnClick">{{btnText}}</button> <img @click="show = false" class="close" src="../assets/imgs/clear.png" alt=""> </div> </transition-group> </template>
index.js檔案,寫方法
import Vue from 'vue' import Popup from './index.vue' const PopupBox = Vue.extend(Popup) Popup.install = function (data) { let instance = new PopupBox({ data }).$mount() document.body.appendChild(instance.$el) Vue.nextTick(() => { instance.show = true // show 和彈窗元件裡的show對應,用於控制顯隱 }) } export default Popup
main.js引入vue元件
import Popup from "./components/popup/index"
Vue.prototype.$popup = Popup.install
元件中使用方法
btnClick() {
this.$popup({
imgUrl: require('../assets/imgs/test_result.png'), // 頂部圖片
imgLoadTip:'圖片載入中...',
title: '我是標題',
content: '我是內容',
btnText: '我是按鈕',
click: () => {
// 點選按鈕事件
// this.$router.push('……')
console.log(`點選按鈕了!`)
},
})
},
至此,一個全域性彈框元件就完成 了!