编写下面的代码:
<el-table-column
v-for="(th, key) in tableHeader"
v-if="!checkNotAnyAuth(th)"
:key="key"
:prop="th.prop"
:label="th.label"
:fixed="th.fixed"
:min-width="th.minWidth"
:width="th.width"
align="center"
element-loading-text="拼命加载中"
>
在编写代码保存,运行之后报错:
The 'tableHeader' variable inside 'v-for' directive should be replaced with a computed property that returns filtered array instead. You should not mix 'v-for' with 'v-if'
如图:
中文意思是:'v-for’指令中的’tableHeader’变量应该被替换为一个计算属性,返回过滤后的数组。你不应该把v-for和v-if混在一起
我们可理解为:
在进行项目开发的时候因为在一个标签上同时使用了v-for和v-if两个指令导致的报错。
原因:v-for的优先级会高于v-if,因此v-if会重复运行在每个v-for中
弊端:这样重复的运算会消耗计算机性能,降低浏览器加载速度,在开发过程中应该尽量避浏览器开不必要性能的消耗
我们可以这样写:使用template标签进行包裹(template为html5的新标签,无特殊含义)
<template v-for="(th, key) in tableHeader">
<el-table-column
v-if="!checkNotAnyAuth(th)"
:key="key"
:prop="th.prop"
:label="th.label"
:fixed="th.fixed"
:min-width="th.minWidth"
:width="th.width"
align="center"
element-loading-text="拼命加载中"
>
</el-table-column>
</template>
注意:key值写el-table-column标签里面
这样就解决了v-for和v-if使用时报错和损耗性能问题。
最后,欢迎各位小伙伴留言,或者点个关注,以后我会不定期更新我的技术博客。同时,在遇到问题时候可以私信我,我们大家一起解决!