Vue3封装函数式组件

MyDialog.vue

<template>
  <div class="dialog" v-if="isVisible">
    <div class="dialog-content">
      <h2>{{ title }}h2>
      <p>{{ message }}p>
      <div class="dialog-buttons">
        <button @click="confirm">确认button>
        <button @click="cancel">取消button>
      div>
    div>
  div>
template>

<script>
import { ref } from 'vue';

export default {
  props: {
    title: {
      type: String,
      required: true
    },
    message: {
      type: String,
      required: true
    }
  },
  emits: ['confirm', 'cancel'],
  setup(props, { emit }) {
    const isVisible = ref(true);

    function confirm() {
      isVisible.value = false;
      emit('confirm');
    }

    function cancel() {
      isVisible.value = false;
      emit('cancel');
    }

    return {
      isVisible,
      confirm,
      cancel
    };
  }
};
script>

<style scoped>
.dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-content {
  background-color: #fff;
  padding: 20px;
  text-align: center;
}

.dialog-buttons {
  margin-top: 20px;
}

.dialog-buttons button {
  margin: 0 10px;
}
style>

ShowMyDialog.js

import MyDialog from './MyDialog.vue'
function ShowMyDialog(message,title,onConfirm,onCancel) {
	// id=app已被主App注册,需要避开
    const div = document.createElement('div')
    document.body.appendChild(div)
    // 传入组件,组件属性、事件
    const app = createApp(MyDialog,{
    	title,
    	message,
        onConfirm(){
            onConfirm()
            app.unmount()
            div.remove()
        },
        onCancel(){
            if(onCancel){
                onCancel()
            }
            // 卸载元素
            app.unmount()
            div.remove()
        }
    })
    app.mount(div)
}
export default ShowMyDialog

Use:

methods:{
login(){
ShowMyDialog('hello','world',()=>{console.log('点击了确认')}
}
}

你可能感兴趣的:(javascript,前端,vue.js)