我不确定为什么在下面的代码中计算机属性错误会导致意外的副作用。
错误:
✘ https://google.com/#q=vue%2Fno-side-effects-in-computed-properties Unexpected side effect in "orderMyReposByStars" computed property
src/components/HelloWorld.vue:84:14
return this.myRepos.sort((a, b) => a.stargazers_count < b.stargazers_count)
的HTML:
<div v-if="myRepos && myRepos.length > 0">
<h3>My Repos</h3>
<ul>
<li v-for="repo in orderMyReposByStars" v-bind:key="repo.id">
<div class="repo">
{{repo.name}}
<div class="pull-right">
<i class="fas fa-star"></i>
<span class="bold">{{repo.stargazers_count}}</span>
</div>
</div>
</li>
</ul>
</div>
js:
export default {
name: 'HelloWorld',
data () {
return {
myRepos: null, <-- THIS IS ULTIMATELY AN ARRAY OF OBJECTS
}
},
computed: {
orderMyReposByStars: function () {
return this.myRepos.sort((a, b) => a.stargazers_count < b.stargazers_count)
},
...
据我所知,根据此处的文档,这看起来是正确的https://vuejs.org/v2/guide/list.html#Displaying-Filtered-Sorted-Results
.sort
改变原始数组。为了避免这种情况,请在对数组进行排序之前先对其进行克隆。
.slice()
是克隆数组的最简单方法之一。参见https://stackoverflow.com/a/20547803/5599288return this.myRepos.slice().sort((a, b) => a.stargazers_count < b.stargazers_count)
在旁注,
null.sort()
否则null.slice()
会抛出错误。也许最好将的初始值设置myRepos
为空数组[]
而不是null