vue自定義組件插入到body中的實(shí)現(xiàn)方式
更新時(shí)間:2025年12月13日 14:31:34 作者:@紅@旗下的小兵
文章介紹了如何在Vue中創(chuàng)建一個(gè)自定義的notice提醒組件,并將其插入到body中,該組件通過(guò)調(diào)用`show`方法顯示,調(diào)用`remove`方法銷毀,主要步驟包括創(chuàng)建組件、使用render函數(shù)加載、$mount掛載并插入到body中
vue自定義組件插入到body中
以notice提醒組件為例,調(diào)用組件,如下:
實(shí)現(xiàn)了兩個(gè)方法
- show方法時(shí)顯示組件
- remove方法銷毀組件
// 加載組件
let noticeCom = vm.$create({
title: '提醒標(biāo)題',
content: '提醒內(nèi)容',
duration: 2000 // 組件的顯示時(shí)長(zhǎng)
}).show()
// 銷毀
noticeCom.remove()實(shí)現(xiàn)思路
- (1)首先創(chuàng)建組件
- (2)使用render函數(shù)加載組件
- (3)$mount掛載組件,把組件渲染為真實(shí)dom
- (4)把dom插入到body中去
Notice.vue組件:
<!--Notice.vue組件-->
<template>
<div v-if="isShow" class="notices">
<div>{{title}}</div><div>{{contents}}</div>
</div>
</template>
<script>
export default {
props: {title: String, contents: String, duration: Number},
data() {return {isShow: false}},
methods: {
show() { // show 方法控制組件的顯示
this.isShow = true
let timer = setTimeout(() => {
this.isShow = false
clearTimeout(timer)
}, this.duration)
}
}
}
</script>在main.js中,把渲染Notice組件的方法掛載到vue實(shí)例上:
// main.js 把notice組件渲染掛載到vue實(shí)例上 import notice from "@/components/notice.js" Vue.prototype.$create = notice
notice.js:
// notice.js 加載組件的主文件
import Vue from 'vue'
export default function create(component, props) {
let vm = new Vue({
// 使用render函數(shù)渲染組件
render(h) {
return h(component,{props})
}
}).$mount()
document.body.appendChild(vm.$el) // vm.$el 是Notice組件掛載的根節(jié)點(diǎn)<div class="notices">··· ···</div>
const noticeComponent = vm.$children[0]
// 組件掛載銷毀實(shí)例的方法(實(shí)際就是刪除dom)
noticeComponent.removeNotice = function () {
document.body.remove(vm.$el)
}
return noticeComponent
}總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue-ANTD表單輸入中自定義校驗(yàn)一些正則表達(dá)式規(guī)則介紹
這篇文章主要介紹了Vue-ANTD表單輸入中自定義校驗(yàn)一些正則表達(dá)式規(guī)則介紹,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01
echarts3如何清空上一次加載的series數(shù)據(jù)
這篇文章主要介紹了echarts3如何清空上一次加載的series數(shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10
Vue標(biāo)簽屬性動(dòng)態(tài)傳參并拼接字符串的操作方法
這篇文章主要介紹了Vue標(biāo)簽屬性動(dòng)態(tài)傳參并拼接字符串的操作方法,我們需要根據(jù)傳入值的類型,在placeholder屬性賦值"請(qǐng)輸入長(zhǎng)度",“請(qǐng)輸入寬度”,"請(qǐng)輸入厚度"等提示字符,本文通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友參考下吧2023-11-11
基于Vue3實(shí)現(xiàn)數(shù)字華容道游戲的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用Vue編寫一個(gè)數(shù)字華容道游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
解決ant-design-vue安裝報(bào)錯(cuò)的問(wèn)題
這篇文章主要介紹了解決ant-design-vue安裝報(bào)錯(cuò)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12

