vuejs axios数据未填充

时间:2018-02-14 17:55:38

标签: json vue.js axios

虽然从Axios Get方法填充的VueJS数据可以通过将数据输出到控制台来确认,但我无法从前端访问数据。

这是我的样本JSON输出

{
"locations" : {
    "items" : ["abc","def","ghi"],
    "selectedLocation" : ""
},
"categories" : {
    "items" : {
        "doctor" : ["test", "test2", "test3"],
        "management" : ["test1","test2","test3"]
    },
    "subcategories":[],
    "selectedCategory":"",
    "selectedSubCategory":""
}

这是我的前端代码

<form id="vueAppJobSearchPanel" class="offset-top-10 offset-sm-top-30" action="/job-search">
<div class="group-sm group-top">
    <div style="max-width: 230px;" class="group-item element-fullwidth">
        <div class="form-group">
            <select v-model="locations.selectedLocation" id="form-filter-location" name="loc" data-minimum-results-for-search="Infinity" class="form-control">
                <option value="">{{global.job_search_panel.placeholder_title_location}}</option>
                <option v-for="location in locations.items" :value="location">${location}</option>
            </select>
        </div>
    </div>
    <div style="max-width: 230px;" class="group-item element-fullwidth">
        <div class="form-group">
            <select v-model="categories.selectedCategory" id="form-filter-location" name="cat" data-minimum-results-for-search="Infinity" class="form-control">
                <option value="">{{global.job_search_panel.placeholder_title_category}}</option>
                <option v-for="(category_obj, category) in categories.items" :value="category">${category}</option>
            </select>
        </div>
    </div>
</div></form>

这是我的VueJS和AXIOS代码

const vm = new Vue({
el: '#vueAppJobSearchPanel',
delimiters: ['${', '}'],
data: {
    test: {
        "items" : ["abc","def","ghi"],
        "selectedLocation" : ""
    },
    locations : {},
    categories : {}
},
mounted(){
    this.loadDropDown();
},
methods: {
    loadDropDown : function() {
        let modelName = "CustomModule1";
        let apiUrl = '/api/' + modelName + '/getFields';

        axios.get(apiUrl)
            .then(function (response) {
                this.locations = constructLocationDropDownValues(response, modelName);
                this.categories = constructCategorySubCategoryDropDownValues(response, modelName);
            })
            .catch(function (error) {
                console.log(error);
            });
    }
}});

loadDropDown函数中的this.locations返回一个有效的JSON。但是JSON没有传递给前端(即HTML)。当我尝试输出“locations”时,它将返回一个空的{}

想法?谢谢

1 个答案:

答案 0 :(得分:2)

问题在于axios回调中的'this'。您应该使用箭头功能来保持上下文

axios
    .get(apiUrl)
    .then(response => {
      this.locations = constructLocationDropDownValues(response, modelName)
      this.categories = constructCategorySubCategoryDropDownValues(response,modelName)
    })
    .catch(function (error) {
      console.log(error)
    })