http request で得た値をprops として子component にパスした時、mounted で値を加工しようとしたらprops の取得タイミングの都合で正しいprops の値を取得しないで処理されてしまうエラーの回避。さらにその値を編集したい場合。
環境:
vue@2.6.12
@親コンポーネント
axios.get(****).then((res) => {
this.forChildComponent = res.data
})
<some-childComponent :forChildComponent=forChildComponent>
@子コンポーネント
props: ['forChildComponent']
created や mounted で値に操作しようとすると http request のレスポンスによって値が正しく取得できるか左右する
** ダメなケース
mounted() {
this.targetValue = this.forChildComponent + 1
}
>>>> http request のレスポンスが遅いと undefined + 1 になってしまう
** Need fix
computed: {
targetValue() {
return this.forChildComponent + 1
}
}
>>> 値は正しく取得できる。targetValue に追加処理が発生しないのならこれでOK
** Solution さらにforChildComponent を編集する必要がある場合
data() {
return {
newValue: ''
}
},
computed: {
targetValue() {
if(newValue) {
return newValue
} else {
return this.forChildComponent + 1
}
}
},
methods: {
changeTargetValue() {
this.newValue = 9
}
}
直接 props を編集しようとすると
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders.
とエラーが出るので新たに newValue を設定してエラーを回避