🖥
#Vue – mutating a prop directly since the value will be overwritten wh
Guide
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
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
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。
公開日時
2020-05-06
Discussion