vue如何封装组件和用方法调用
简单封装一个message提示组件~~~~
注意:此组件的样式依赖bootstrap
1、 message.vue组件封装
<template>
<teleport to="#message">
<div :class="[classObject, 'alert', 'wrap']" v-if="isVisible">
<span>{{ message }}</span>
<button type="button" class="btn-close float-end" aria-label="Close" @click="close"></button>
</div>
</teleport>
</template>
<script setup lang="ts">
import { ref, reactive, PropType, onBeforeMount, onUnmounted } from 'vue'
type Alerttype = "success" | 'danger' | 'primary'
const isVisible = ref<boolean>(true);
const props = defineProps({
type: {
default: 'success',
type: String as PropType<Alerttype>
},
message: {
default: 'message',
type: String || Number
}
})
const classObject = reactive({
'alert-success': props.type == 'success',
'alert-danger': props.type == 'danger',
'alert-primary': props.type == 'primary',
})
const close = () => {
isVisible.value = false;
}
const createdMessageId = () => {
const node = document.createElement("div");
node.id = "message";
document.body.appendChild(node);
}
onBeforeMount(() => {
createdMessageId();
})
onUnmounted(() => {
let node: (HTMLElement | null) = document.getElementById('message');
if (node) {
document.body.removeChild(node)
}
})
</script>
<style scoped >
.wrap {
width: 300px;
}
</style>
2、方法调用
import { createApp } from 'vue'; "vue"
import Message from '../components/message.vue';
type messageType = "success" | 'danger' | 'primary';
/*
createApp 第一个参数是组件,第二个参数是prop
*/
export const createcreMessage = (message:string,type:messageType,timeout=2000)=>{
const messageInstance = createApp(Message,{
message,
type
})
const node:HTMLDivElement = document.createElement("div");
document.body.appendChild(node);
messageInstance.mount(node)
setTimeout(() => {
if(node){
messageInstance.unmount();
document.body.removeChild(node);
}
}, timeout);
}
3、unmount方法说明
Vue.js中的destroy和unmount都是用于组件的销毁。
destroy是Vue.js生命周期中的一个钩子函数,用于在实例销毁之前进行清理工作,包括解绑事件、销毁子组件等。在Vue.js中,可以通过在组件定义时添加destroyed钩子函数来实现这一过程。
而unmount指的是从DOM中卸载组件。在Vue.js 3.0中,unmount被作为卸载组件的新方法,取代了之前的$destroy方法。unmount方法用于从父组件卸载并销毁组件实例,同时也会卸载所有子组件。在Vue.js 3.0中,可以使用unmount来代替destroyed钩子函数来卸载组件。
因此,destroyed是Vue.js的生命周期方法,用于组件实例在销毁前进行清理工作,而unmount是Vue.js 3.0中用于卸载组件的方法,并不是钩子函数。
4、createApp方法说明
返回一个提供应用上下文的应用实例。应用实例挂载的整个组件树共享同一个上下文。
1、使用
const app = Vue.createApp({
data() {
return {
...
}
},
methods: {...},
computed: {...}
...
},{根prop参数}) 会传递给应用程序
5、组件使用方法
- 直接引入组件即可使用
- 方法调用 引入createcreMessage,createcreMessage(message,type)即可使用