[英]Vuejs generate elements from object inside components
我正在嘗試創建一個組件,該組件將以Vuex狀態渲染VueJs虛擬dom內部的元素。
問題是我收到此錯誤,但我不明白為什么以及如何解決它
避免將觀察到的數據對象用作vnode數據:{“ class”:“ btn btn-default”}始終在每個渲染器中創建新的vnode數據對象!
在我的Vuex狀態內,我存儲並定義了元素屬性的對象
{
type: 'a',
config: {
class: 'btn btn-default',
},
nestedElements: [
{
type: 'span',
value: 'test',
},
{
type: 'i',
},
],
},
我的組件代碼看起來像
methods: {
iterateThroughObject(object, createElement, isNestedElement = false) {
const generatedElement = [],
nestedElements = [];
let parentElementConfig = {};
for (const entry of object) {
let nodeConfig = {};
if (typeof entry.config !== 'undefined' && isNestedElement) {
nodeConfig = entry.config;
} else if (typeof entry.config !== 'undefined') {
parentElementConfig = entry.config;
}
if (entry.nestedElements) {
nestedElements.push(this.iterateThroughObject(entry.nestedElements, createElement, true));
}
if (!isNestedElement) {
nodeConfig = parentElementConfig;
}
generatedElement.push(createElement(
entry.type,
nodeConfig === {} ? entry.value : nodeConfig,
nestedElements
));
}
if (isNestedElement) {
return generatedElement;
}
return createElement('ul', generatedElement);
},
},
render(createElement) {
const barToolsElements = this.$store.state.titleBar.barToolsElements;
if (barToolsElements) {
return this.iterateThroughObject(barToolsElements, createElement);
}
return false;
},
當我嘗試傳遞我的上一個generatedElement.push()
定義時,將產生錯誤。 因為entry.value
是{"class":"btn btn-default"}
。
我不明白為什么它告訴我重新創建一個新的Vnode對象,而此值僅使用一次。
我想念或誤解了嗎?
可能是因為您正在傳遞對商店狀態下的對象的引用,這可能無意間導致了它們的突變。 傳遞這些對象時,請嘗試為其創建深層克隆 ,例如..
nodeConfig = JSON.parse(JSON.stringify(entry.config));
parentElementConfig = JSON.parse(JSON.stringify(entry.config))
;
nodeConfig === {} ? JSON.parse(JSON.stringify(entry.value)) : nodeConfig,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.