我正在尝试使用 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/