我尝试使用Axios从mySQL数据库中获取数据,以设置用vue.js-formulate生成的表单输入的初始值。
下面是我的脚本,我想在这里设置“question1”的初始值:
new Vue({
el: '#app',
created() {
this.fetchData();
},
data: {
row: "",
values: {
question1: this.row["answerq1"],
}
},
methods: {
fetchData() {
axios.get('retrieve.php')
.then(function (response) {
this.row = response.data;
// Checking output in Console:
console.log(this.row["answerq1"]);
});
},
}
})fetchData()函数按预期工作,this.row"answerq1“打印预期的字符串。但是,在数据部分中访问此值会产生"this.row是未定义的“错误。我猜想它与已创建()钩子的生命周期有关,但我无法理解。
发布于 2022-11-04 13:39:18
this.row是API请求之前的空字符串,因此不能访问this.row["answerq1"]。您需要等待API请求完成。
做出这一改变,它应该能发挥作用:
data() {
return {
row: "",
values: {
question1: "" // set to empty string
}
};
}发布于 2022-11-06 09:11:58
我为遇到类似问题的人找到了我问题的答案:
new Vue({
el: '#app',
created() {
this.fetchData();
},
data: {
row: [],
values: {
question1: null
}
},
methods: {
fetchData() {
axios.get('retrieve.php')
.then((response) => {
this.row = response.data;
this.values.question1 = this.row["answerq1"];
});
},
}
})https://stackoverflow.com/questions/74317727
复制相似问题