为什么vue.js会改变我的JSON数据?

时间:2017-12-25 10:50:27

标签: javascript json vuejs2

我想从我的API返回数据并将其显示在vue.js项目中。 数据是:

{  
   "pages":[  
      {  
         "id":3,
         "slug":"over-mij",
         "updated_at":"2017-12-25T11:16:21+01:00",
         "created_at":"2017-12-25T10:56:21+01:00",
         "title":"Over mij",
         "content":""
      },
      {  
         "id":6,
         "slug":"mijn-cv",
         "updated_at":"2017-12-25T11:07:29+01:00",
         "created_at":"2017-12-25T11:07:29+01:00",
         "title":"Mijn cv",
         "content":null
      }
   ],
   "current_user":null
}

然后我使用vue-resource从我的API页面加载vuex的单独模块中的数据:

const actions = {
    initPages({commit}) {
        Vue.resource('pages').get({}).then(function(response) {
            if (response) {
                response.json().then(data => {
                    state.pages = data;
                });
            }
        });
    }
}

然而问题是当我检查state.pages中的内容时,它包含:

{
  "pages": {
    "pages": [
      {
        "id": 3,
        "slug": "over-mij",
        "updated_at": "2017-12-25T11:16:21+01:00",
        "created_at": "2017-12-25T10:56:21+01:00",
        "title": "Over mij",
        "content": ""
      },
      {
        "id": 6,
        "slug": "mijn-cv",
        "updated_at": "2017-12-25T11:07:29+01:00",
        "created_at": "2017-12-25T11:07:29+01:00",
        "title": "Mijn cv",
        "content": null
      }
    ],
    "current_user": null
  }
}

由于一些奇怪的原因我的JSON响应被改变了,我已经尝试将state.pages设置为data.pages,这只是消除了第一页对象而不是第二页。

当我将state.pages设置为data.pages [0]时,它确实有效,有人知道为什么会这样吗?

即使我使用突变,我仍然有同样的问题:

store.js的模块:

import Vue from 'vue';

const state = {
    pages: []
}

const mutations = {
    'setPages' (state, pages) {
        state.pages = pages;
    }
}

const getters = {
    pages(state) {
        return state.pages;
    },
    page(state) {
        return keyword =>  state.pages.find(function(page) {
            return page.slug === keyword;
        });
    }
}

const actions = {
    initPages({commit}) {
        Vue.resource('pages').get({}).then(function(response) {
            if (response) {
                response.json().then(data => {
                    commit('setPages', data.pages);
                });
            }
        });
    }
}

export default {
    state,
    getters,
    mutations,
    actions
}

0 个答案:

没有答案