npm方式:
npm install -D unplugin-vue-components unplugin-auto-import
yarn 方式 :
yarn add unplugin-vue-components;
yarn add unplugin-auto-import;
使用官方的这个:
vite.config.js中配置
plugins: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [VantResolver(), ElementPlusResolver()],
}),
],
LoginDialog.js定义
import {createApp} from 'vue'
import SubDialog from './LoginDialog.vue'
/**
* 关键函数挂在整个页面上去
*/
const createDialog = () => {
const mountNode = document.createElement('div')
mountNode.setAttribute('id', 'dialog-mask-dialog')
const Instance = createApp(SubDialog, {
show: true,
close: () => {
Instance.unmount(mountNode);
document.body.removeChild(mountNode);
}
})
document.body.appendChild(mountNode)
Instance.mount(mountNode)
}
export default createDialog
LoginDialog.vue 定义
<template>
<Teleport to="body">
<el-dialog
v-model="props.show"
title="登录"
width="500px"
center
>
<el-form :model="loginForm" :rules="formDataRule" ref="formRef" label-width="120px">
<el-form-item label="用户名" prop="phone">
<el-input v-model="loginForm.phone" placeholder="输入手机号"/>
</el-form-item>
<el-form-item label="验证码" prop="verifyCode">
<div style="display: inline-block">
<el-input v-model="loginForm.verifyCode" placeholder="输入验证码"/>
</div>
<div style="display: inline-block">
<el-button>获取验证码</el-button>
</div>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitLogin(formRef)">登录</el-button>
</el-form-item>
</el-form>
</el-dialog>
</Teleport>
</template>
<script setup>
import {reactive, ref} from "vue";
const formRef = ref(null)
const loginForm = reactive({
phone: '',
verifyCode: ''
})
const formDataRule = {
phone: [{required: true, message: '手机号不能为空', trigger: 'blur'}],
verifyCode: [{required: true, message: '验证码不能为空', trigger: 'blur'}]
}
const props = defineProps({
show: {
type: Boolean,
default: false
}
})
const submitLogin = (ref) => {
ref.validate((valid) => {
if (valid) {
console.log('submit!')
} else {
console.log('error submit!')
return false
}
})
}
</script>
<style scoped>
</style>