将数据放入prop中以使其看起来整洁Vue.js [英] Putting data inside prop to make it look tidy Vue.js
问题描述
我有一个创建页面,我使用Axios发出POST请求,并且效果很好.但是我认为我的代码根本不健康.
I have a create page, I make a POST request using Axios and it works great. But I think my code is not healthy at all.
这就是我定义道具的方式:
data () {
return {
first_name: '',
last_name: '',
student_number: '',
phone_number: '',
email: '',
birth_date: '',
school_name: '',
};
},
这些是 v-model
的对象.我使用它们向我的API发出POST请求.但是,我可以将它们放在一个数组或一个道具中,而不是一个一个地写它们吗?
These things are v-model
's objects. I use them to make a POST request to my API. But instead of writing them one by one, can I put these in an array or a prop?
向API提出请求时,我会一次又一次地定义我的 v-model
.
When I'm making a request to API, I define my v-model
's one by one again.
赞
axios.post(`/api/students`, {
first_name:this.first_name,
last_name:this.last_name,
student_number:this.student_number,
phone_number:this.phone_number,
email:this.email,
birth_date:this.birth_date,
school_name:this.school_name,
我可以只发送一两行吗?
Can I send them in just one or two line?
例如: postedData:this.studentData;
推荐答案
尽管对于此特定用例,上一个答案是正确的,但是如果您要添加不想发送的属性,则它将无法正常工作不再.更好的方法是将所有这些属性放在对象中,让我们将其命名为 studentData
,如下所示:
While the previous answer is correct for this particular use-case, if you were to add properties that you don't want to send, it wouldn't work anymore. A better approach is to put all those properties inside an object, let's name it studentData
, like this:
data() {
return {
studentData: {
first_name: '',
last_name: '',
student_number: '',
phone_number: '',
email: '',
birth_date: '',
school_name: '',
},
};
}
然后您就可以
axios.post('/api/students', this.studentData);
请注意,您还需要更新 v-model
,例如 v-model ="studentData.first_name"
,而不是 v-model="first_name"
.
Note that you'll also need to update your v-model
s like v-model="studentData.first_name"
instead of v-model="first_name"
.
这篇关于将数据放入prop中以使其看起来整洁Vue.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!