Instead, use a data or computed property based on

2020-03-12 05:52发布

Well, I'm trying to change a value of "variable" in Vue, but when I click on the button they throw a message in console:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "menuOpen"

I have no idea how to solve this problem...

My file.vue:

<template>
  <button v-on:click="changeValue()">ALTERAR</button>
</template>

<script>

export default {
  name: 'layout',
  props: [ 'menuOpen' ],
  methods: {
    changeValue: function () {
      this.menuOpen = !this.menuOpen
    }
  },
}

</script>

Any one can help me? Thanks

1条回答
三岁会撩人
2楼-- · 2020-03-12 06:30

The warning is pretty clear. In your changeValue method you are changing the value of the property, menuOpen. This will change the value internally to the component, but if the parent component has to re-render for any reason, then whatever the value is inside the component will be overwritten with the current state outside the component.

Typically you handle this by making a copy of the value for internal use.

export default {
  name: 'layout',
  props: [ 'menuOpen' ],
  data(){
      return {
          isOpen: this.menuOpen
      }
  },
  methods: {
    changeValue: function () {
      this.isOpen= !this.isOpen
    }
  },
}

If you need to communicate the change of the value back to the parent, then you should $emit the change.

changeValue: function () {
    this.isOpen= !this.isOpen
    this.$emit('menu-open', this.isOpen)
}
查看更多
登录 后发表回答