一段簡短的代碼片段,描述了 $element('id') 被分配給成員變量并發(fā)生堆棧溢出的問題,以及修復它的解決方案。
將通過獲取的內(nèi)容?$element('id')
?賦值給成員變量時,?RangeError: Maximum call stack size exceeded
?可能會發(fā)生棧溢出(),導致程序崩潰。如果某個 DOM 存在成員變量引用,并且成員變量發(fā)生變化,也會發(fā)生堆棧溢出。示例代碼如下: <template>
<template>
<div id="content">
<input type="button" class="button" @click="onTestClick" value="Stack overflow occurs."/>
<text>{{ stateText }}</text>
</div>
</template>
<script>
export default {
private: {
mContentNode: null,
stateText: 'init state'
},
onReady() {
/* When data obtained by $element('id') is assigned to a member variable, a stack overflow may occur. */
this.mContentNode = this.$element('content')
},
onTestClick() {
/* To reproduce this problem, change a member variable when member variable references exist for a DOM. */
this.stateText = 'new state'
}
}
</script>
原因是賦值會導致海量的數(shù)據(jù)變化。從而導致內(nèi)部異常循環(huán),導致棧溢出。
解決方案
為了防止堆棧溢出,你可以將通過獲取的數(shù)據(jù)分配給?$element('id')
?局部或全局變量而不是成員變量。示例代碼如下:
<script>
let $gContentNode = null
export default {
private: {
stateText: 'init state'
},
onReady() {
/* You can assign the data obtained through $element('id') to a local or global variable to prevent the stack overflow. */
const cContentNode = this.$element('content')
$gContentNode = this.$element('content')
},
onTestClick() {
this.stateText = 'new state'
}
}
</script>