我在谷歌上没有找到任何解决方案,也许我理解错了我的问题。
所以我想在 vue.js 中编写一个可重用的函数,它从数据库的特定表中获取数据。
一切正常,只是最后一部分,将结果插入应用数据。
正如您在代码中看到的,我创建了数据字段health_weights
,它与 mysql 数据库表同名,以获取不同权重的列表。
目标是对不同的数据库表也使用相同的函数,如 animals_groups
或 car_speeds
并保持相同的函数,如 getData("animals_groups")
或 getData("car_speeds")
。
然后该函数将从 php 脚本中获取列表(工作正常)。
然后将数据放入 vue 应用程序数据数组,如 health_weights[]
或 animal_groups[]
(这是行不通的)。
希望有一个我不知道的简单解决方案。
谢谢
我尝试在数据属性中使用变量,但没有用
// Template
<div class="list">
<div v-for="(weights, index) in health_weights" :key="index">
<p>{{weights.created}} x {{weights.weight}}kg</p>
</div>
</div>
// Script
<script>
var app = new Vue({
el: '#weight',
data: {
health_weights: [],
},
created(){
this.getData("health_weights");
},
methods: {
getData: function(table){
var bodyFormData = new FormData();
bodyFormData.set('type', "getData");
bodyFormData.set('table', table);
axios({
method: 'post',
url: 'api/health.php',
data: bodyFormData,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
//app.health_weights = JSON.parse(response.data);
app.table = response.data;
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
},
},
})
</script>
我在前端没有收到任何错误,只是一个空列表。
最佳答案
您应该使用箭头函数 (response)=>{}
以正确访问 vue 实例 (this
),并且您可以访问数据属性如下:
this[table]=....
this
指的是你的 vue 实例。
HTML
<div class="list">
<div v-for="(weights, index) in health_weights" :key="index">
<p>{{weights.created}} x {{weights.weight}}kg</p>
</div>
</div>
VUEJS
<script>
var app = new Vue({
el: '#weight',
data(){
return{
health_weights: [],
}
},
created(){
this.getData("health_weights");
},
methods: {
getData: function(table){
var bodyFormData = new FormData();
bodyFormData.set('type', "getData");
bodyFormData.set('table', table);
axios({
method: 'post',
url: 'api/health.php',
data: bodyFormData,
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then((response) =>{
//app.health_weights = JSON.parse(response.data);
this[table] = response.data;
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
},
},
})
</script>
关于javascript - 如何将我的方法参数放入数组属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57547083/