ElementUI?$notify通知方法中渲染自定義組件實現(xiàn)
一、背景
ElementUI 的 Notification 組件通常用于全局的通知提醒消息,其中展示內(nèi)容默認是文本字符串,當然也可以設置 dangerouslyUseHTMLString: true 后傳入 HTML 片段。
如果要展示比較復雜的動態(tài)內(nèi)容,一般會把傳入的內(nèi)容封裝成組件,而直接傳入組件是無法渲染的,本文就是解決 $notify 中怎么渲染自定義組件的問題。

Vue && Notification
最近開發(fā)項目遇到一個數(shù)據(jù)同步延遲的問題,就是在提交表單后,創(chuàng)建或編輯的操作不能馬上同步更新。最后討論的解決辦法就是在提交表單之后,前端輪詢一個獲取狀態(tài)的接口,并在全局展示一個進度條,實時更新進度,所以就使用了 Notification 組件。
二、問題解析
this.$notify 方法中有一個 message 參數(shù),類型為 string/Vue.VNode。要想渲染一個自定義組件,關鍵就是要把自定義組件轉(zhuǎn)化為 Vue.VNode。
Vue全局提供了一個 this.$createElement 方法就是專門干這個的,用法和 render 函數(shù)中參數(shù) createElement 一致 (createElement: () => VNode) => VNode。
三、具體實現(xiàn)
- 根組件 App.vue
<template>
<div>content</div>
</template>
<script>
import ProgressBar from '@/components/ProgressBar'
export default {
// 注冊自定義組件
components: {
ProgressBar,
},
data() {
return {
progress: 1,
hiveData: {},
}
},
methods: {
showProgress () {
const h = this.$createElement
this.notifyInstance = this.$notify({
title: '數(shù)據(jù)處理進度',
duration: 0,
dangerouslyUseHTMLString: true,
message: h('ProgressBar', { // 使用自定義組件
ref: 'progressBar',
props: {
progress: this.progress,
...this.hiveData,
},
}),
})
},
setProgressVal() {
this.$refs.progressBar &&
this.$refs.progressBar.setProgress(this.progress)
},
}
}
</script>- 自定義組件 ProgressBar.vue
<template>
<div class="global-bar">
<div class="global-bar-label">庫名:【{{ dbName }}】</div>
<div class="global-bar-label">表名:【{{ tableName }}】</div>
<el-progress
:text-inside="true"
:stroke-width="16"
:percentage="progress"
:color="colors"
></el-progress>
<br />
<el-alert
title="關閉或刷新后不再顯示提交進展,請勿關閉或刷新。"
type="warning"
:closable="false"
show-icon
>
</el-alert>
</div>
</template>
<script>
export default {
props: {
dbName: {
type: String,
default: '',
},
tableName: {
type: String,
default: '',
},
},
data() {
return {
progress: 1,
colors: [
{ color: '#f56c6c', percentage: 20 },
{ color: '#e6a23c', percentage: 40 },
{ color: '#6f7ad3', percentage: 60 },
{ color: '#1989fa', percentage: 80 },
{ color: '#5cb87a', percentage: 100 },
],
hiveData: {},
}
},
methods: {
setProgress(progress) {
this.progress = progress
},
},
}
</script>- 注意:
h()方法的第一個參數(shù)要么是原生標簽名,如:div、p、span、h1等,要么就是components中注冊過的自定義組件名,否則無法正常渲染。
以上就是ElementUI $notify通知方法中渲染自定義組件實現(xiàn)的詳細內(nèi)容,更多關于ElementUI $notify自定義組件的資料請關注腳本之家其它相關文章!
相關文章
vue-router使用next()跳轉(zhuǎn)到指定路徑時會無限循環(huán)問題
這篇文章主要介紹了vue-router使用next()跳轉(zhuǎn)到指定路徑時會無限循環(huán)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
vue3 Element-Plus el-backtop無效問題及解決
這篇文章主要介紹了vue3 Element-Plus el-backtop無效問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
Vue 重置data的數(shù)據(jù)為初始狀態(tài)操作
這篇文章主要介紹了Vue 重置data的數(shù)據(jù)為初始狀態(tài)操作方案,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03

