: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-rendersの原因と解消方法
Vue.jsを使っていて、
[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: "count"
というエラーに遭遇した。
ChildComponent内でemitより、親コンポーネントにイベントが渡ってくる。
その値をpropsのcountに格納する流れ。
<template> <h2>タイトル</h2> <p>{{ count }}</p> <ChildComponent @count-up="count = $event"> </template> <script> export default { props: { count: { type: Number, default() { return 0 }, }, } } </script>
この場合、子コンポーネントからpropの値を直接変更しないでと怒られる。
解消方法
emitで変更が加わるcountをpropsではなく、dataで定義するように変更。
<script> export default { data() { return { count: 0 } } } </script>