LoginSignup
7
6

More than 3 years have passed since last update.

[備忘録]axiosのPOSTでVueのobjectが空になってしまう問題

Posted at

Jsの型

typeofでチェックしても、配列、連想配列、VueオブジェクトどれもObjectとして返されるがObjectでもそれぞれ違う。

今回ハマったこと

sample.vue
<script>
data() {
    return {
        object: [] //v-forで動的に生成される
    }
}
methods:{
 post() {
    axios.post('/api/hoge',{
         key1: 'fuga',
         key2: this.object
    }).then(response => {
          console.log(response.data)
 })
} 
~省略
</script>

この時、動的に生成されたobjectはどうやらそのまま、Axiosの第二引数にぶち込んで送ることはできないみたい。サーバーサイドで取得した物をそのまま返してコンソールで確認してもArray(0)になるだけ。

送れるObjectに変換

How to convert the object of Vue to normal object? #292

It is said that JSON.parse (JSON.stringify ()) is a good method in this discussion, but I think that using JSON.stringify is not a good method.
Because Date type etc. are converted to String.
As the most effective means, I think best answer @imbolc 's Object.assign ({}, vm.$data)

Object.assign ({}, vm.$data)

こいつで変換するのが最良だぜ!とのことだったので、、、

sample.vue
<script>
data() {
    return {
        object: [] //v-forで動的に生成される
    }
}
methods:{
 post() {
    var convert = Object.assign({},this.object)
    axios.post('/api/hoge',{
         key1: 'fuga',
         key2: convert
    }).then(response => {
          console.log(response.data)
 })
} 
~省略
</script>

コンソールでそのまま全部返した物を確認すると

console
{
  key1: 'fuga',
  key2: {name: value, name2: value2}
}

ちゃんと送れた模様

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6