【问题标题】:Vue: Proper way to mutate props passed to component?Vue:改变传递给组件的道具的正确方法?
【发布时间】:2021-05-26 12:16:35
【问题描述】:

在下面的伪代码中,我有一个父组件,其初始数据为nameages,我将它们作为道具传递给child-component

我的child-component 将它们作为道具,但如果我想改变道具怎么办。例如,假设我想反转 name 属性字符串。或者如果我想pop() ages 数组的最后一个年龄?我是否必须将这些道具设置为子组件中的初始数据?

家长

<template>

      <child-component :name=name :ages=ages></child-component>
</template>


data() {
    return {
        name: "Alex",
        ages: [23,41,94],
    }
}

儿童

props: {
    name: {type: String},
    ages: {type: Array},
}

【问题讨论】:

  • 然后你用.sync修饰符传递它们,例如child-component :name.sync="name" 并在子组件中使用 this.$emit('name', newValue)
  • 这能回答你的问题吗? Vue 2 - Mutating props vue-warn

标签: vue.js vuejs2 vue-component


【解决方案1】:

您不应该改变子组件中的道具。这不是一个好习惯。 见Vue 2 - Mutating props vue-warn

【讨论】:

【解决方案2】:

编辑:也可以与这样的计算设置器配对完成

export default {
  props: ['propText'],
  data() {
    return {
      dataText: ''
    }
  },
  computed: {
    textValue: {
      get () {
        return this.dataText || this.propText
      },
      set (newValue) {
        this.dataText = newValue
      }
    }
  }
}

您有多种方法,例如将您的逻辑用于 computed(并直接显示),将 prop 值复制到 data(并在那里对其进行变异/处理)或将值发送回父级然后对孩子进行修改。

Michael Thiessen 的这篇文章对这个主题很好:https://michaelnthiessen.com/avoid-mutating-prop-directly/

一个例子sn-p

export default {
  name: 'ReversedList',
  props: {
    list: {
      type: Array,
      required: true,
    }
  },
  computed: {
    reversedList() {
      return this.list.reverse();
    }
  }
};

【讨论】:

  • 感谢@kissu。但是,如果我将其设为计算属性,我不会失去在该组件内动态改变它的能力吗?就像我得到的那样,我可以让计算属性执行类似 return this.list.reverse() 的操作,但这并不像将其设置为 data 那样灵活,然后随时用它做任何我想做的事情
  • 您实际上可以做很多事情,但您也可以将其复制到 mounted 上的 data(我猜)或使用计算设置器的组合,我刚刚编辑了我的答案以显示例子。
猜你喜欢
  • 1970-01-01
  • 2020-01-08
  • 2020-12-04
  • 2019-12-27
  • 1970-01-01
  • 1970-01-01
  • 2019-11-12
  • 2018-10-05
  • 2021-12-02
相关资源
最近更新 更多