【问题标题】:Update props value in vue [duplicate]更新vue中的道具值[重复]
【发布时间】:2022-01-05 17:10:23
【问题描述】:

vue中如何通过方法更新props值? 所以我有默认值为 20 的道具宽度

<div :style="{ width: width+ 'px'}">
props: {
  width: {
    type: [String, Number],
    default: '20px'
  },
}

然后它会将组件渲染为width=20px。我可以使用 javascript 更改道具值吗?示例它可能看起来像这样(?)

myEventHandler(e) {
  if(window.innerWidth < 768 && this.width === '20')
  this.width = '' // I want to revert the value to empty like it never used this props before. But I get vue warn that the prop being mutated
},

任何帮助都会非常有帮助,谢谢!

【问题讨论】:

  • 您不应该从子组件更新 prop 值。您可以向父级发送一个事件,以便它更新道具中给定的值,或者您可以使用子级数据中的中间值,当道具更改时更新。

标签: javascript vue.js vuejs2


【解决方案1】:

如 VueJs 文档中所述:https://vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow

这意味着你不应该尝试改变孩子内部的道具 零件。如果你这样做了,Vue 会在控制台中警告你。

如果你真的需要改变 props,你可以尝试类似的方法: 在子组件中:

props: {
  width: {
    type: [String, Number],
    default: '20px'
  }
},
computed: {
  computedWidth: {
    get(){
      return this.width
    },
    set(newValue) {
      this.$emit('widthChanged', newValue)
    }
  }
}

在父组件中:

<child-component
  :width="width"
  @widthChanged="someFunctionWhoMutateYourVar"
>

这应该做的工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-01
    • 2018-03-25
    • 2018-01-10
    • 2018-12-24
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    相关资源
    最近更新 更多