🖥

#Vue – mutating a prop directly since the value will be overwritten wh

2023/09/01に公開

Guide

https://vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow

NOTE

You should have like "local variable in child component" by

copy props to data or use computed

子compnentでpropsの値を直接変更すると、親componentが再描画されたときに上書きされてしまう
かわりに props の値をもととした data や computed として扱おう

pages/counters.vue

<template>
  <div>
    <h2>
      parentCount: {{ parentCount }}
    </h2>
    <input type="button" @click="incrementParentCounter" value="Increment Parent">
    <input type="button" @click="reset" value="reset Parent">
    <LocalCounter :count="parentCount"/>
    <LocalCounter :count="parentCount"/>
  </div>
</template>

<script>
import LocalCounter from '~/components/LocalCounter.vue'

export default {
  data () {
    return {
      parentCount: 1
    }
  },
  components: {
    LocalCounter
  },
  methods: {
    incrementParentCounter (e) {
      this.parentCount += 1
    },
    reset (e) {
      this.parentCount = 1
    },
  }
}
</script>

components/LocalCounter.vue

// https://vuejs.org/v2/guide/components-props.html

// 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: "count"


<template>
  <div>
    <h2>
      Count: {{ localCount }}
    </h2>
    <input type="button" @click="incrementCounter" value="Increment!">
  </div>
</template>

<script>
export default {
  props: {
    count: {
      type: Number
    }
  },
  data: function () {
    return {
      localCount: this.count
    }
  },
  methods: {
    incrementCounter (e) {
      this.localCount = this.localCount + 1
    }
  }
}
</script>

View

You can increment each child counter
You can

image
image
image
image

Warned child component example

<template>
  <div>
    <h2>
      Count: {{ count }}
    </h2>
    <input type="button" @click="incrementCounter" value="Increment!">
  </div>
</template>

<script>
export default {
  props: {
    count: {
      type: Number,
      default: 1
    },
  },
  methods: {
    incrementCounter (e) {
      this.count = this.count + 1
    }
  }
}
</script>

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/3142

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2020-05-06

Discussion