封装一个组件通过接口调用

858 阅读1分钟

在vue项目中可能在不同的页面出现相同弹窗或者其他的需求,想通过js来调用接口来显示的话,就可以通过extend来实现。下面的演示是通过一个简单的案例来解释这种场景

1630056261(1).jpg

先定义一个模板cpopup.vue

<template>
  <transition name="fade" mode="out-in" v-if="isShow">
    <div class="mask" @touchmove.prevent>
      <div class="mask-window">
        <div class="mask-title">{{title}}</div>
        <div class="mask-content">
          {{content}}
        </div>
        <div class="mask-footer">
          <div @click="onCancel">{{cancelText}}</div>
          <div @click="onConfirm">{{confirmText}}</div>
        </div>
      </div>
    </div>
  </transition>
</template>
<script>
  export default {
    name: 'index',
    data () {
      return {
        title: '提示',
        content: null,
        cancelText: '取消',
        confirmText: '确认',
        cancel: function () {},
        confirm: function () {},
        isShow: false

      }
    },
    methods: {
      onCancel () {
        this.isShow = false
        this.cancel()
      },
      onConfirm () {
        this.isShow = false
        this.confirm()
      }
    }
  }
</script>
<style scoped>
  #app{
    overflow: hidden;
  }
  .mask{
    width: 100%;
    height: 100%;
    position: fixed;
    left: 0;
    top: 0;
    background: rgba(0,0,0,0.3);
  }
  .mask-title {
	  width: 100%;
	  padding: 0px 20px;
	  box-sizing: border-box;
	  text-align: center;
	  font-size: 18px;
	  font-weight: bold;
  }
  .mask-window{
    padding-top: 20px;
    width: 80%;
    background: white;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
  }
  .mask-content{
    padding: 20px;
    text-align: center;
  }
  .mask-footer{
    height: 45px;
    display: flex;
  }
  .mask-footer>div{
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
  }
  .mask-footer>div:active{
    background: #fafafa;
  }
  .mask-footer>div:nth-child(1){
    color: gray;
  }

</style>

定义一个组件的index.js

import Vue from 'vue'
import cPopup from './cpopup.vue'

const PopupBox = Vue.extend(cPopup)
cPopup.install = function (data) {
  let instance = new PopupBox({
    data
  }).$mount()

  document.body.appendChild(instance.$el)

  Vue.nextTick(() => {
    instance.isShow = true
  })
}

export default cPopup

在main.js引入

import cPopup from './component/cpopup/index'
Vue.prototype.$cPopup = cPopup.install

在需要使用的页面

this.$cPopup({
    title: '提示', // 弹窗标题
    content: '测试自定义弹窗', // 弹窗内容
    cancelText: '取消', // 左边按钮文本
    confirmText: '确认', // 右边按钮文本
    isSync: true, // 是否异步
    cancel: () => {
            // 点击左边按钮事件
            console.log('取消')
    },
    confirm: () => {
            // 点击右边按钮事件
            console.log('确定')
    }
})