使用Vue封装一个弹窗组件
弹窗属于通用型的功能,在各个场景中都可能用到。开发仅需要一次,使用却需要很多次,因此着重考虑使用时的成本。
组件式
<template>
<div id="modal">
<div id="box">
<div id="text">{{ msg }}</div>
<Button @click="emit('click')"></Button>
</div>
</div>
</template>
<script setup>
import Button from "~/components/Button.vue";
const emit = defineEmits(['click']);
defineProps({
msg:{
type:String,
required:true
}
})
</script>
<style scoped>
.modal{
...
}
.box{
...
}
.text{
...
}
</style>
开发十分简单,但是使用呢?
<!-- App.vue -->
<template>
<div>
<Button @click="clickHandler">显示弹窗</Button>
<MessageBox v-if="showMsg" :msg="msg" @click="clickHandler"></MessageBox>
</div>
</template>
<script setup>
import { ref } from 'vue';
import Button from "~/components/Button.vue";
import MessageBox from "~/components/MessageBox.vue";
const showMsg=ref(false);
const msg=ref('提示消息');
const clickHandler = () => {
showMsg.value=!showMsg.value
};
</script>
是否十分甚至九分麻烦?
By MFJip
继续阅读