【问题标题】:Vuejs Prop keeps changingVuejs Prop 不断变化
【发布时间】:2018-11-11 08:09:45
【问题描述】:

基本上我正在对一个从道具获取其值的数组进行排序,因为我们知道道具值不会改变(或者至少这是我在文档中读到的)但是当我对我的数组进行删除时,它也会影响道具:

props: ['allquestions','getskills'],
data() {
  return {
    getskillsnew: this.getskills,
    searchwindow: true,
    allquestionsnew: this.allquestions,
  }
},
methods: {
  filterop(value){
    for (i = this.allquestionsnew.length - 1; i >= 0; --i) {
      if (this.allquestionsnew[i].lastweek === 0) {
        this.$delete(this.allquestionsnew, i);
      }
      setTimeout(() => {
        this.searchwindow = true;
      }, 1000) 
    }
  }
}

所以在 for 循环完成后,我检查了我的道具(所有问题),它已被削减到 5,就像 this.allquestionsnew 一样,但我想要的是这个拼接只对 this.allquestionsnew 生效而不是道具!

我怎样才能做到这一点?谢谢

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    在 JavaScript 中,数组是通过引用传递的。来自Vue docs..

    请注意,JavaScript 中的对象和数组是通过引用传递的,所以 如果 prop 是数组或对象,则改变对象或数组本身 子组件内部影响父状态。

    要解决这个问题,您需要为您的数组创建一个deep clone。例如..

    data() {
       return {
          getskillsnew:this.getskills,
          searchwindow:true,
          allquestionsnew: JSON.parse(JSON.stringify(this.allquestions)),
       }
    
    },
    

    这只会在创建组件时初始化allquestionsnew 数组。如果您需要在道具更改时更新其值,您可以使用观察者来完成。

    【讨论】:

      【解决方案2】:

      这不是一个好习惯。如果你有道具 - 那么你应该通过父母影响它。如果你想设置一些数据等于你的道具,那么在生命周期钩子中做:

      created() {
          this.allquestionsnew = [...this.allquestions]
      }
      

      如您所见,这里我使用了数组解构(ES6)。这会比你做的好得多。

      【讨论】:

        猜你喜欢
        • 2020-08-27
        • 2018-10-05
        • 2021-04-06
        • 2017-07-25
        • 1970-01-01
        • 2019-08-05
        • 2018-08-23
        • 2019-02-16
        • 2016-05-29
        相关资源
        最近更新 更多