如何使用来自ajax的数据填充vuetify选择框

时间:2018-04-18 20:37:20

标签: javascript vue.js vuetify.js

我正在尝试使用ajax调用中检索到的数据填充vuetify选择框。我不确定如何使用此数据填充选择框。 ajax调用工作,我得到一个对象数组,我设置等于项目。这就是我的尝试:

V-选择

<v-select
:items="items"
item-text="test"
v-model="client"
label="Choose a Client"
class="input-group--focused"
item-value="text"
></v-select>

获取客户端功能

getClient: function (items) {
        axios.get('http://127.0.0.1:8000/client/')
        .then(function (response, items) {
            console.log(response.data);
            items  = response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
    }
    }

通话功能

created() {
    this.getClient(this.items);

    }

1 个答案:

答案 0 :(得分:1)

参数通过引用的(值)传递,这就是为什么当您在items函数中分配 getClient时,它不会影响this.items

直接使用this.items

created() {
    this.getClient();                                   // removed this.items
},
methods: {
    getClient: function () {                            // replaced `function (items) {` with `function () {`
            axios.get('http://127.0.0.1:8000/client/')
            .then((response) => {                       // replaced `function (response, items) {` with `(response) => {`
                console.log(response.data);
                this.items  = response.data;            // used `this.items = ` instead of `items = `
            })
            .catch(function (error) {
                console.log(error);
            });
        }
    }

重要提示:请注意我已更换:

.then(function (response, items) {
    console.log(response.data);
    this.items = response.data;
})

使用

.then((response) => {                // using arrow function now
    console.log(response.data);
    this.items = response.data;
})

这很重要,因为thisthis.items = response.data;在您使用function () { 时未指向Vue实例,但在您使用时会执行此操作箭头功能。

这是因为每个function () {}都有自己的上下文(自己的this),可以将其设置为其他内容。箭头函数otoh继承了声明它的上下文(this)。在这种情况下,由于您在方法中声明它,this是Vue实例。使用箭头功能可以保持它。使用function()并不能保证(this可以设置为其他内容,这可能会发生)。

有关详细信息,我建议MDN - Arrow Functions

相关问题