javascript - 如何使用 ajax 数据填充 vuetify 选择框

标签 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);

    }

最佳答案

参数通过引用(值)传递,这就是为什么当您在 getClient 函数内分配 items 时,它不会影响 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;
})

这很重要,因为 this (在 this.items = response.data; 中)当您使用 时不会指向 Vue 实例function () {,但是当您使用箭头函数时它会发生。

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

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

关于javascript - 如何使用 ajax 数据填充 vuetify 选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49908637/

相关文章:

javascript - 缺少网络共享 API 权限

vue.js - v-if 可以触发什么吗? v-if 是否引发事件?

javascript - Vue SPA 在嵌套 Promise 中检索错误代码(不是 200)的状态代码

css - 如何更改 v-text-field 中的占位符/标签颜色?

JavaScript : Uncaught SyntaxError: Unexpected token <

javascript - 获取一个图片元素的当前图片源

rest - Vue如何向服务器提交信息?

vue.js - 在 v-data-table Vuetify 中添加超链接

javascript - Vuetify 自动完成,接受列表外的值

javascript - 将带有 HTML 字符串的数组返回到 jquery $.post 方法