彈窗組件及其回調函數


博客地址:https://ainyi.com/83

常見的 Element 組件的 MessageBox 彈窗組件,調用方法:

this.$confirm('xxx') 

還可以增加其回調方法:

this.$confirm('這是一條信息').then(() => {
  console.log('確定了')
}).catch(() => {
  console.log('關閉了')
})

實現方法

首先在 packages 文件夾下新建 confirm 文件夾,往里面新建 src 目錄,存放源代碼

src 下新建 Confirm.vue 文件寫好相關彈窗的 html、js 代碼

應用時有相關的回調函數,相應的實現方法就是使用Promise實現

<template>
  <div>
    ...
  </div>
</template>
<script>
export default {
  name: 'confirm',
  data() {
    return {
      promptMessage: '',
      modelOperate: '確認',
      confirmVisible: false,
      resolve: '', // promise,類型 function
      reject: '' // promise,類型 function
    }
  },
  watch: {},
  computed: {
    showClass() {
      return this.confirmVisible ? 'view' : ''
    }
  },
  mounted() {},
  created() {},
  filters: {},
  methods: {
    close() {
      this.reject() // catch 獲取
      this.confirmVisible = false
    },
    confirm() {
      this.resolve() // then 獲取
      this.confirmVisible = false
    }
  }
}
</script>

在 Confirm.vue 同級目錄下新建 main.js

import Main from './Confirm.vue'
import Vue from 'vue'

let ConfirmConstructor = Vue.extend(Main)
let instance, params

const Confirm = function(options) {
  return new Promise((resolve, reject) => { // eslint-disable-line
    if (typeof options === 'string') {
      params = {
        promptMessage: options,
        resolve: resolve, // 將 resolve、reject 傳到組件內調用
        reject: reject
      }
    } else {
      params = {
        ...options,
        resolve: resolve,
        reject: reject
      }
    }
    showConfirm()
  })
}

const showConfirm = () => {
  let options = params || {}
  instance = new ConfirmConstructor({
    data: options
  })
  instance.$mount() // 掛載
  document.body.appendChild(instance.$el)
  instance.confirmVisible = true
}

export default Confirm

然后在上級目錄(Confirm 文件夾)下新建 index.js 文件導出

import Confirm from './src/main'
export default Confirm

然后再最外層的 index.js 整合

import Confirm from './confirm'

const install = function(Vue, opts = {}) {
  Vue.prototype.$confirm = Confirm
}

/* istanbul ignore if */
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue)
}

export default {
  Confirm,
  install
}

最后就可以通過文章最頂部的調用方式愉快地玩耍了

博客地址:https://ainyi.com/83


免責聲明!

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



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