我不知道为什么我的计算机属性错误会产生意外的副作用,如下所示.
错误:
? 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)
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
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)
},
...
Run Code Online (Sandbox Code Playgroud)
据我所知,这看起来是正确的https://vuejs.org/v2/guide/list.html#Displaying-Filtered-Sorted-Results
Jac*_*Goh 27
.sort 改变原始数组.
要避免它,请在排序之前克隆该数组.
.slice()克隆数组是最简单的方法之一.请参阅/sf/answers/1438346241/
return this.myRepos.slice().sort((a, b) => a.stargazers_count < b.stargazers_count)
在旁注,null.sort()或null.slice()将抛出错误.也许最好将初始值设置myRepos为空数组[]而不是null