繁体   English   中英

如何在 Vue.JS 中使用 axios 方法填充组件的数据

[英]How to populate component's data with axios method in Vue.JS

我想使用 Axios 的方法填充组件数据。 但是,使用 Axios,组件数据始终是未定义的。 如果我不使用 Axios(对返回值进行硬编码),则组件数据会正确填充。

data () {
    return {
        myData: this.getData();
    }
},

methods:{
    getData(){
        axios({
          method: 'GET',
          url   : 'Department/GetAllForDropdown',
        }).then(function (response){
            return response.data;
        });
    }
}

我如何在不使用传统填充方式的情况下实现这一目标,例如

.then(function (response){
    self.myData = response.data;
})

谢谢你。

========编辑========

我有一个动态表单生成器。 我正在使用 vuetify。 它根据我声明的数据创建表单组件。

<template>
    <div v-for="formItem in formDetails.formInfo">
        <v-text-field 
        v-if="formItem.type != 'select'
        :label="formItem.placeholder"
        v-model="formItem.value"
        ></v-text-field>

        <v-select
        v-if="formItem.type == 'select'
        :items="formItem.options"
        :label="formItem.placeholder"
        v-model="formItem.value"
        ></v-select>
    </div>
</template>


data () {
    return {
        formDetails: {
            title: 'myTitle',
            formInfo:[
                {
                  type:'text',
                  placeholder:'Name*',
                  value: '',
                },
                {
                  type:'select',
                  placeholder:'Option1*',
                  options: this.getOptions1(),
                  value: '',
                },
                {
                  type:'select',
                  placeholder:'Option2*',
                  options: this.getOptions2(),
                  value: '',
                },
            ]
        },
    }
},

methods:{
    getOptions1(){
        var self = this;
        axios({
          method: 'GET',
          url   : 'Department1/GetAllForDropdown',
        }).then(function (response){
            return response.data;
        });
    },
    getOptions2(){
        var self = this;
        axios({
          method: 'GET',
          url   : 'Department2/GetAllForDropdown',
        }).then(function (response){
            return response.data;
        });
    }
} 

我目前坚持使选择框动态化,因为我计划传入诸如

options: this.getOptions1(),

让他们获得选择框中的所有选项。

谢谢你。

这个想法仍然是将响应分配给项目并在加载时留下一个占位符。

getOptions(formItem) {
  formItem.loading = true;
  var placeholder = formItem.placeholder;
  formItem.placeholder = "Loading... Please wait";
  axios({
    method: "GET",
    url: "Department1/GetAllForDropdown"
  }).then(function(response) {
    formItem.loading = false;
    formItem.placeholder = placeholder;
    formItem.options = response.data;
  });
}

我写了一个小演示 你可以试试看。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM