2016-11-16 39 views
2

我想加載一個JSON文件的內容到我的vuejs應用程序並在我的組件中訪問它。我能夠通過創建一個API來加載JSON到vuex店:主VUE實例的創建功能加載json的數據到vuex存儲和訪問組件

import Vue from 'vue'; 

const Http = new Vue(); 

export function getData() { 
    return Http.$http.get('./app/assets/content/en_uk.json') 
    .then(response => Promise.resolve(response.data)) 
    .catch(error => Promise.reject(error)); 
} 

和動作

export const getSiteContent = ({commit}) => { 
    api.getData().then(data => { 
    commit('siteContent', data); 
    }); 
}; 

我跑getSiteContent

export default new Vue({ 
    el: '#root', 
    store, 
    router, 
    created() { 
    getSiteContent(store); 
    }, 
    render: h => h('router-view') 
}); 

在chrome中使用vue調試工具我可以看到商店

export const state = { 
    isSearching: false, 
    searchQuery: '', 
    siteData: {}, 
    filteredComponents: [], 
    hasResults: false, 
    activeComponent: null 
}; 

通過siteData進行更新。

這是JSON的一部分:在我的組件一樣{{mumbo}}我弄不懂的不確定PROJECT_NAME財產

{ 
    "global": { 
    "project_name": { 
     "text": "Project title" 
    }, 
    "search": { 
     "form_placeholder": { 
     "text": "Search..." 
     }, 
     "no_results": { 
     "text": "Sorry no results for '{0}' was found" 
     }, 
     "search_text": { 
     "text": "You are searching for '{0}' and there are {1} found" 
     } 
    } 
    } 
} 

當我嘗試訪問

computed: { 
     ...mapGetters(['siteData']), 
     mumbo() { 
     return this.siteData.global.project_name; 
     } 
    } 

我覺得這是因爲它沒有翻倒,當我將它設置爲返回siteData.global

我不知道如果我做錯事或我缺少一個連接的時間問題讓這個工作。

回答

1

正如你所猜測的,這裏的問題是Vue試圖訪問siteData內容的那個計算屬性,而數據仍在加載。雖然最初siteData是一個有效的對象,但試圖訪問siteData.global.project_name失敗,因爲siteData在數據尚未加載時沒有字段global。爲了防止錯誤,你將不得不包括像這樣的檢查:

mumbo() { 
    return this.siteData.global ? this.siteData.global.project_name : 'Loading...'; 
} 

爲了說明這個解決方案,下面是根據你的代碼的簡單JSFiddle

+0

感謝您的這一點,我已經測試過,這個工程。我只是想知道是否有其他方法呢?還是我在做一切應該怎麼做? – saunders

+0

就我個人而言,我認爲這是一個很好的模式和應該完成的方式。另一種方法是在Vue組件初始化之前加載數據,但通常類似這樣的事情要複雜得多...... – Aletheios

+0

如果我想在組件加載之前加載數據,可以指出我的方向請看 – saunders