计算属性中的意外副作用 [英] Unexpected side effect in computed property

查看:74
本文介绍了计算属性中的意外副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么我在使用下面的代码时在计算机属性错误中遇到了意外的副作用.

错误:

 ✘ https://google.com/#q=vue%2Fno-side-effects-in-computed-properties orderMyReposByStars"计算属性中的意外副作用src/components/HelloWorld.vue:84:14return this.myRepos.sort((a, b) => a.stargazers_count 

html:

<div v-if="myRepos && myRepos.length > 0"><h3>我的仓库</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>

js:

出口默认{name: 'HelloWorld',数据 () {返回 {myRepos: null, <-- 这最终是一个对象数组}},计算:{orderMyReposByStars: 函数 () {return this.myRepos.sort((a, b) => a.stargazers_count 

据我所知,根据此处的文档,这看起来是正确的 https://vuejs.org/v2/guide/list.html#Displaying-Filtered-Sorted-Results

解决方案

.sort 改变原始数组.

为了避免它,在排序之前先克隆数组.

.slice() 是克隆数组的最简单方法之一.请参阅 https://stackoverflow.com/a/20547803/5599288

return this.myRepos.slice().sort((a, b) => a.stargazers_count

<小时>

附带说明,null.sort()null.slice() 会抛出错误.也许将 myRepos 的初始值设置为空数组 [] 而不是 null

会更好

I'm not sure why i'm getting an unexpected side effect in computer property error with the code below.

Error:

 ✘  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)
    },
...

From what I can tell this looks correct according to the docs here https://vuejs.org/v2/guide/list.html#Displaying-Filtered-Sorted-Results

解决方案

.sort mutates the original array.

To avoid it, clone the array before sorting it.

.slice() is 1 of the simplest way to clone array. See https://stackoverflow.com/a/20547803/5599288

return this.myRepos.slice().sort((a, b) => a.stargazers_count < b.stargazers_count)


on a side note, null.sort() or null.slice() will throw error. Perhaps it would be better to set the initial value of myRepos to empty array [] instead of null

这篇关于计算属性中的意外副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆