Vue動態(tài)組件實現異常處理方法
動態(tài)組件有兩種常用場景:
一是動態(tài)路由:
// 動態(tài)路由 export const asyncRouterMap: Array<RouteRecordRaw> = [ { path: '/', name: 'index', meta: { title: '首頁' }, component: BasicLayout, // 引用了 BasicLayout 組件 redirect: '/welcome', children: [ { path: 'welcome', name: 'Welcome', meta: { title: '引導頁' }, component: () => import('@/views/welcome.vue') }, ... ] } ]
二是動態(tài)渲染組件,比如在 Tabs 中切換:
<el-tabs :model-value="copyTabName" type="card"> <template v-for="item in tabList" :key="item.key || item.name"> <el-tab-pane :name="item.key" :label="item.name" :disabled="item.disabled" :lazy="item.lazy || true" > <template #label> <span> <component v-if="item.icon" :is="item.icon" /> {{ item.name }} </span> </template> // 關鍵在這里 <component :key="item.key || item.name" :is="item.component" v-bind="item.props" /> </el-tab-pane> </template> </el-tabs>
在 vue2 中使用并不會引發(fā)什么其他的問題,但是當你將組件包裝成一個響應式對象時,在 vue3 中,會出現一個警告:
Vue received a Component which was made a reactive object. This can lead to unnecessary performance overhead, and should be avoided by marking the component with markRaw
or using shallowRef
instead of ref
.
出現這個警告是因為:使用 reactive 或 ref(在 data 函數中聲明也是一樣的)聲明變量會做 proxy 代理,而我們組件代理之后并沒有其他用處,為了節(jié)省性能開銷,vue 推薦我們使用 shallowRef 或者 markRaw 跳過 proxy 代理。
解決方法如上所說,需要使用 shallowRef 或 markRaw 進行處理:
對于 Tabs 的處理:
import { markRaw, ref } from 'vue' import A from './components/A.vue' import B from './components/B.vue' interface ComponentList { name: string component: Component // ... } const tab = ref<ComponentList[]>([{ name: "組件 A", component: markRaw(A) }, { name: "組件 B", component: markRaw(B) }])
對于動態(tài)路由的處理:
import { markRaw } from 'vue' // 動態(tài)路由 export const asyncRouterMap: Array<RouteRecordRaw> = [ { path: '/', name: 'home', meta: { title: '首頁' }, component: markRaw(BasicLayout), // 使用 markRaw // ... } ]
而對于 shallowRef 和 markRaw,2 者的區(qū)別在于 shallowRef 只會對 value 的修改做出反應,比如:
const state = shallowRef({ count: 1 }) // 不會觸發(fā)更改 state.value.count = 2 // 會觸發(fā)更改 state.value = { count: 2 }
而 markRaw,是將一個對象標記為不可被轉為代理。然后返回該對象本身。
const foo = markRaw({}) console.log(isReactive(reactive(foo))) // false // 也適用于嵌套在其他響應性對象 const bar = reactive({ foo }) console.log(isReactive(bar.foo)) // false
可看到,被 markRaw 處理過的對象已經不是一個響應式對象了。
對于一個組件來說,它不應該是一個響應式對象,在處理時,shallowRef 和 markRaw 2 個 API,推薦使用 markRaw 進行處理。
以上就是淺析Vue3動態(tài)組件怎么進行異常處理的詳細內容,有不當的地方還請大家多多指教
到此這篇關于Vue動態(tài)組件實現異常處理方法的文章就介紹到這了,更多相關Vue動態(tài)組件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
教你使用vue-autofit 一行代碼搞定自適應可視化大屏
這篇文章主要為大家介紹了使用vue-autofit 一行代碼搞定自適應可視化大屏教程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05使用VUE+iView+.Net Core上傳圖片的方法示例
這篇文章主要介紹了使用VUE+iView+.Net Core上傳圖片的方法示例,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01