标签:zip vue compute method 事件监听 而且 组件 com 字符
看了掘金一篇关于Vue开发相关优化技巧,确实发现以前项目中写的代码有些问题,但是无关逻辑问题,当时写的代码感觉加载编译,甚至逻辑都没有问题,但是现在想一下,确实是有一些优化方面的问题,也就是说以前写的代码的确是有一些问题的。所以看了这篇帖子,借此总结一下。
<template>
<div class="zjy">
<div class="item" v-for=‘(val,index) in list‘ :key=‘index‘ v-if=‘val.isShow‘>{{val.value}}</div>
</div>
</template>
<script>
export default {
data(){
return{
list:[]
}
},
methods:{
getData(){
this.$axios.get(‘/getData/zjy‘).then((res)=>{
this.list = res.data
}).catch((err)=>{
})
}
}
}
</script>
这种代码的意图无非就是isShow == true才展示item。但是文档中建议不要将v-for与v-if一起使用。可以这样处理,
getData(){
this.$axios.get(‘/getData/zjy‘).then((res)=>{
this.list = res.data.filter((item)=>{
return item.isShow
})
}).catch((err)=>{
})
}
或是这样处理
<template>
<div class="zjy">
<div class="item" v-for=‘(val,index) in handleList‘ :key=‘index‘>{{val.value}}</div>
</div>
</template>
<script>
export default {
data(){
return{
list:[]
}
},
computed:{
handleList(){
return this.list.filter((item) => {
return item.isShow
})
}
},
methods:{
getData(){
this.$axios.get(‘/getData/zjy‘).then((res)=>{
this.list = res.data
}).catch((err)=>{
})
}
}
}
</script>
当使用index下标作为key的值,也就是index作为标识的时候。当插入一条数据,列表中后面的key都发生了变化,那么当前的v-for都会对key变化的element重新渲染,但是其实除了插入的element数据其他的都没有发生变化,这就导致了没有必要的开销。所以建议使用数据中唯一的,如ID等字段。或是特殊字符串拼接index的形式
<template>
<div class="zjy">
<div class="item" v-for=‘(val,index) in handleList‘ :key=‘$index‘+index>{{val.value}}</div>
</div>
</template>
v-for将数据遍历出来,滚动到底部的时候就继续请求 API 。随着数据的加载,DOM会越来越多,这样就导致了性能开销的问题产生了,当页面上的DOM太多的时候,难免给客户端造成一定的压力(页面卡顿,滑动不流畅,渲染时间长),有个很重要的概念(只有出现在视图上的DOM才是重要的DOM),所以建议应用虚拟列表的概念,网上有一些很好的解决方案:vue-virtual-scroller 库。// require法 component: resolve=>(require([‘@/components/HelloWorld‘],resolve)) // import component: () => import(‘@/components/HelloWorld‘)
<div v-if="status===‘ok‘">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>
如果像上面的 div 只是为了切换条件而存在,还导致元素层级嵌套多一层,那么它没有“存在的意义”。我们都知道在声明页面模板时,所有元素需要放在 <template> 元素内。除此之外,它还能在模板内使用,<template> 元素作为不可见的包裹元素,只是在运行时做处理,最终的渲染结果并不包含它。
<template>
<div>
<template v-if="status===‘ok‘">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</template>
</div>
</template>
同样的,我们也可以在 <template> 上使用 v-for 指令,这种方式还能解决 v-for 和 v-if 同时使用报出的警告问题。
<template v-for="item in 10">
<div v-if="item % 2 == 0" :key="item">{{item}}</div>
</template>
标签:zip vue compute method 事件监听 而且 组件 com 字符
原文地址:https://www.cnblogs.com/zhenjianyu/p/13381732.html