- 首页
- 前端开发
- 如何使用 vue 提交从对象数组中提取数据的预填充表单
如何使用 vue 提交从对象数组中提取数据的预填充表单
[英] How to submit a prefilled form pulling data from an array of objects using vue
本文介绍了如何使用 vue 提交从对象数组中提取数据的预填充表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于我的学校项目,我正在制作一个遛狗网络应用程序,我正在尝试创建一个表单来更新用户拥有的狗的信息.
此信息存储在一个对象数组中,其中每个对象都包含一条狗的信息,我正在使用 v-for
为数组中的每条狗调用一个表单,这是第一个组件:
<div class="body"><h1 class="mt-3">Tus perros</h1><b-row class="mt-1"><div class="cards mx-5 mb-5"><更新宠物v-for="宠物中的宠物":key="pet.id":宠物=宠物":currentUser="当前用户":title="pet.dog_name"标签=文章"样式="最大宽度:17rem;"类=卡"></更新宠物>
</b-row>
</模板><脚本>从 'vuex' 导入 { mapState };从 '@/components/Update/UpdatePets.vue' 导入 UpdatePets;导出默认{name: "DogsComponente",组件:{更新宠物},数据() {返回 {当前用户: {},宠物:[],}},创建(){如果(localStorage.getItem(宠物")){尝试 {this.pets = JSON.parse(localStorage.getItem("pet"));}赶上(e){localStorage.removeItem("宠物");}}如果(localStorage.getItem(用户")){尝试 {this.currentUser = JSON.parse(localStorage.getItem("user"));}赶上(e){localStorage.removeItem("用户");}}this.getMascotas();},方法: {getMascotas(){this.$store.dispatch("getMascotaById", {cadena: this.currentUser.user});}},};<style lang="scss" 作用域>h1{颜色:#40db9a;}.身体 {边距:0;高度:自动;显示:网格;地点项目:中心;溢出:隐藏;}.cards {显示:弹性;}.卡片 {颜色:#063869;背景颜色:#eef6e1;边界半径:1rem;填充:1.5rem;box-shadow: 3px 3px 12px 2px rgba(black, 0.6);过渡:0.2s;}.card:not(:first-child) {左边距:-2rem;}.card:not(:last-child):hover,.card:not(:last-child):focus-within {变换:translateY(-1rem);~ .card {变换:translateX(2rem);}}</风格>
如您所见,我使用 v-for
为数组中的每个宠物调用 UpdatePets
表单,这是 UpdatePets<的代码/code> 组件:
<div class="body"><b-row class="mt-1"><div class="cards mx-5 mb-5"><b-form @submit.prevent="updateMascota" class="pl-4"><b-form-group id="input-group-1" label="Nombre:" label-for="input-1"><b-表单输入id="输入-1"v-model="提议的狗名"必需的只读></b-form-input></b-form-group><b-形式-组id="输入组-2"标签=拉扎:"label-for="input-2"><b-表单输入id="输入-2"v-model="提议的DogRace"必需的></b-form-input></b-form-group><b-形式-组id="输入组-3"label="Altura en cm:"label-for="input-3"><b-表单输入id="输入-3"v-model="proposedDogHeight"必需的分钟=0"></b-form-input></b-form-group><b-形式-组id="输入组-4"标签="比索和公斤:"label-for="input-4"><b-表单输入id="输入-4"v-model="提议的狗重量"必需的分钟=0"></b-form-input></b-form-group><b-形式-组id="输入组-4"label="Edad en años:"label-for="input-4"><b-表单输入id="输入-4"v-model="proposedDogAge"类型=数字"分钟=0"必需的></b-form-input></b-form-group><b-形式-组id="输入组-6"标签=算法mas?:"label-for="input-6"><b-form-textareaid="输入-6"v-model="提议的DogNotes"行=3"最大行数 =6"></b-form-textarea></b-form-group><b-button block pie type="submit" variant="success">更新数据</b-button></b-form>
</b-row>
</模板><脚本>导出默认{道具:['宠物','currentUser'],name: "DogsComponente",数据() {返回 {当前用户: {},宠物:[],建议狗名:"",提议的DogRace: "",建议狗高度:"",建议狗重量:",建议狗年龄:",建议狗注:"}},安装(){如果(localStorage.getItem(宠物")){尝试 {this.pets = JSON.parse(localStorage.getItem("pet"));this.proposedDogName = this.pets.dog_namethis.proposedDogRace = this.pets.dog_racethis.proposedDogHeight = this.pets.dog_heightthis.proposedDogWeight = this.pets.dog_weightthis.proposedDogAge = this.pets.dog_agethis.proposedDogNotes = this.pets.dog_notes}赶上(e){localStorage.removeItem("宠物");}}如果(localStorage.getItem(用户")){尝试 {this.currentUser = JSON.parse(localStorage.getItem("user"));}赶上(e){localStorage.removeItem("用户");}}this.getMascotas();},方法: {getMascotas(){this.$store.dispatch("getMascotaById", {cadena: this.currentUser.user});},更新Mascota(){this.$store.dispatch("updateMascota", [{dog_name: this.proposedDogName,dog_race: this.proposedDogRace,dog_height: this.proposedDogHeight,dog_weight:this.proposedDogWeight,dog_age:this.proposedDogAge,dog_notes: this.proposedDogNotes,}, "宠物"]).then(({数据}) => {如果(数据==="){警报(错误 alactualizar datos");} 别的 {警报(已实现")location.reload();}});},},};<style lang="scss" 作用域>h1{颜色:#40db9a;}.身体 {边距:0;高度:自动;显示:网格;地点项目:中心;溢出:隐藏;}.cards {显示:弹性;}.卡片 {颜色:#063869;背景颜色:#eef6e1;边界半径:1rem;填充:1.5rem;box-shadow: 3px 3px 12px 2px rgba(black, 0.6);过渡:0.2s;}.card:not(:first-child) {左边距:-2rem;}.card:not(:last-child):hover,.card:not(:last-child):focus-within {变换:translateY(-1rem);~ .card {变换:translateX(2rem);}}</风格>
问题是它不起作用,它没有预填表单,我所做的只是尝试调整一些我知道它可以在我更新用户信息的地方工作的代码,这是该组件的代码, 完美运行:
<div class="home"><div class="body"><h1>Actualiza Datos de Usuario</h1><div class="SignUp"><img height="300" src="@/assets/Images/Usuario(1).png" alt="图片槽"/><b-form @submit.prevent="updateUsuario" class="pl-4"><b-form-group id="input-group-1" label="用户 ID:" label-for="input-1"><b-表单输入id="输入-1"v-model="proposedClientUser"必需的只读></b-form-input></b-form-group><b-形式-组id="输入组-2"label="Tu contraseña:"label-for="input-2"><b-表单输入id="输入-2"v-model="proposedClientPassword"类型=密码"必需的></b-form-input></b-form-group><b-形式-组id="输入组-3"label="Tu Nombre Completo:"label-for="input-3"><b-表单输入id="输入-3"v-model="proposedClientName"必需的></b-form-input></b-form-group><b-形式-组id="输入组-4"label="Tu numero de celular:"label-for="input-4"><b-表单输入id="输入-4"v-model="proposedClientPhone"类型=数字"必需的></b-form-input></b-form-group><b-形式-组id="输入组-5"label="Tu correo electronico:"label-for="input-5"><b-表单输入id="输入-5"v-model="proposedClientEmail"类型=电子邮件"必需的></b-form-input></b-form-group><b-形式-组id="输入组-6"label="Tu Direccion:"label-for="input-6"><b-表单输入id="输入-6"v-model="proposedClientAddress"必需的></b-form-input></b-form-group><b-button块药片类型="提交"变体="成功">Actualiza tus datos</b-button></b-form>
</模板><脚本>从 'vuex' 导入 { mapState };导出默认{名称:更新客户端",数据() {返回 {当前用户:{},提议的客户用户:"",提议的客户密码:"",提议的客户名称:"",提议的客户电话:"",提议的客户电子邮件:"",提议的客户地址:""};},方法: {updateUsuario() {this.$store.dispatch("updateUsuario", [{用户:this.proposedClientUser,密码:this.proposedClientPassword,客户端名称:this.proposedClientName,client_phone: this.proposedClientPhone,client_e_mail: this.proposedClientEmail,client_address: this.proposedClientAddress}, "客户"]).then(({数据}) => {如果(数据==="){警报(错误 alactualizar datos");} 别的 {警报(已实现")this.$store.dispatch("注销");location.replace('/登录');}});},},创建(){如果(localStorage.getItem(用户")){尝试 {this.currentUser = JSON.parse(localStorage.getItem("user"));this.proposedClientUser = this.currentUser.userthis.proposedClientPassword = this.currentUser.passwordthis.proposedClientName = this.currentUser.client_namethis.proposedClientPhone = this.currentUser.client_phonethis.proposedClientEmail = this.currentUser.client_e_mailthis.proposedClientAddress = this.currentUser.client_address}赶上(e){localStorage.removeItem("用户");}}}};<风格>.身体 {底边距:20px;}</风格>
任何帮助将不胜感激 这是一张显示 vue devtools 的图像,您可以看到表格不是预填充,你也可以看到数组
解决方案
- 在
UpdatePets.vue
中你已经在props上声明了pets
和currentUser
,不需要在中再次声明数据()
- 在主
.vue
文件上,你传递了 pet
属性,同时 UpdatePets.vue
接受 pets
> prop,将UpdatePets.vue
上的prop从pets
改为pet
除此之外,它应该可以正常工作.检查我在这里制作的极简演示:https://codesandbox.io/s/priceless-elbakyan-ef2qu?file=/src/App.vue
For my school project, I'm making a dog walker web app, I'm trying to create a form to update the information about the dogs that a user owns.
This information is stored in an array of objects, where each object contains the info of a dog, I'm using a v-for
where I call a form for each dog in the array, here's the first component:
<template>
<div class="body">
<h1 class="mt-3">Tus perros</h1>
<b-row class="mt-1">
<div class="cards mx-5 mb-5">
<UpdatePets
v-for="pet in pets"
:key="pet.id"
:pet="pet"
:currenUser="currentUser"
:title="pet.dog_name"
tag="article"
style="max-width: 17rem;"
class="card">
</UpdatePets>
</div>
</b-row>
</div>
</template>
<script>
import { mapState } from 'vuex';
import UpdatePets from '@/components/Update/UpdatePets.vue';
export default {
name: "DogsComponente",
components: { UpdatePets },
data() {
return {
currentUser: {},
pets: [],
}
},
created() {
if (localStorage.getItem("pet")) {
try {
this.pets = JSON.parse(localStorage.getItem("pet"));
} catch (e) {
localStorage.removeItem("pet");
}
}
if (localStorage.getItem("user")) {
try {
this.currentUser = JSON.parse(localStorage.getItem("user"));
} catch (e) {
localStorage.removeItem("user");
}
}
this.getMascotas();
},
methods: {
getMascotas(){
this.$store.dispatch("getMascotaById", {
cadena: this.currentUser.user
});
}
},
};
</script>
<style lang="scss" scoped>
h1 {
color: #40db9a;
}
.body {
margin: 0;
height: auto;
display: grid;
place-items: center;
overflow: hidden;
}
.cards {
display: flex;
}
.card {
color: #063869;
background-color: #eef6e1;
border-radius: 1rem;
padding: 1.5rem;
box-shadow: 3px 3px 12px 2px rgba(black, 0.6);
transition: 0.2s;
}
.card:not(:first-child) {
margin-left: -2rem;
}
.card:not(:last-child):hover,
.card:not(:last-child):focus-within {
transform: translateY(-1rem);
~ .card {
transform: translateX(2rem);
}
}
</style>
As you can see, I use a v-for
to call the UpdatePets
form for each pet in the array, here's the code for the UpdatePets
component:
<template>
<div class="body">
<b-row class="mt-1">
<div class="cards mx-5 mb-5">
<b-form @submit.prevent="updateMascota" class="pl-4">
<b-form-group id="input-group-1" label="Nombre:" label-for="input-1">
<b-form-input
id="input-1"
v-model="proposedDogName"
required
readonly
>
</b-form-input>
</b-form-group>
<b-form-group
id="input-group-2"
label="Raza:"
label-for="input-2"
>
<b-form-input
id="input-2"
v-model="proposedDogRace"
required
>
</b-form-input>
</b-form-group>
<b-form-group
id="input-group-3"
label="Altura en cm:"
label-for="input-3"
>
<b-form-input
id="input-3"
v-model="proposedDogHeight"
required
min="0"
>
</b-form-input>
</b-form-group>
<b-form-group
id="input-group-4"
label="Peso en Kg:"
label-for="input-4"
>
<b-form-input
id="input-4"
v-model="proposedDogWeight"
required
min="0"
></b-form-input>
</b-form-group>
<b-form-group
id="input-group-4"
label="Edad en años:"
label-for="input-4"
>
<b-form-input
id="input-4"
v-model="proposedDogAge"
type="number"
min="0"
required
></b-form-input>
</b-form-group>
<b-form-group
id="input-group-6"
label="Algo mas?:"
label-for="input-6"
>
<b-form-textarea
id="input-6"
v-model="proposedDogNotes"
rows="3"
max-rows="6"
>
</b-form-textarea>
</b-form-group>
<b-button block pill type="submit" variant="success">
Actualizar datos</b-button>
</b-form>
</div>
</b-row>
</div>
</template>
<script>
export default {
props: ['pets', 'currentUser'],
name: "DogsComponente",
data() {
return {
currentUser: {},
pets: [],
proposedDogName: "",
proposedDogRace: "",
proposedDogHeight: "",
proposedDogWeight: "",
proposedDogAge: "",
proposedDogNotes: ""
}
},
mounted() {
if (localStorage.getItem("pet")) {
try {
this.pets = JSON.parse(localStorage.getItem("pet"));
this.proposedDogName = this.pets.dog_name
this.proposedDogRace = this.pets.dog_race
this.proposedDogHeight = this.pets.dog_height
this.proposedDogWeight = this.pets.dog_weight
this.proposedDogAge = this.pets.dog_age
this.proposedDogNotes = this.pets.dog_notes
} catch (e) {
localStorage.removeItem("pet");
}
}
if (localStorage.getItem("user")) {
try {
this.currentUser = JSON.parse(localStorage.getItem("user"));
} catch (e) {
localStorage.removeItem("user");
}
}
this.getMascotas();
},
methods: {
getMascotas(){
this.$store.dispatch("getMascotaById", {
cadena: this.currentUser.user
});
},
updateMascota() {
this.$store.dispatch("updateMascota", [{
dog_name: this.proposedDogName,
dog_race: this.proposedDogRace,
dog_height: this.proposedDogHeight,
dog_weight: this.proposedDogWeight,
dog_age: this.proposedDogAge,
dog_notes: this.proposedDogNotes,
}, "pets"])
.then(({ data }) => {
if (data === "") {
alert("Error al actualizar datos");
} else {
alert ("Has actualizado tus datos")
location.reload();
}
});
},
},
};
</script>
<style lang="scss" scoped>
h1 {
color: #40db9a;
}
.body {
margin: 0;
height: auto;
display: grid;
place-items: center;
overflow: hidden;
}
.cards {
display: flex;
}
.card {
color: #063869;
background-color: #eef6e1;
border-radius: 1rem;
padding: 1.5rem;
box-shadow: 3px 3px 12px 2px rgba(black, 0.6);
transition: 0.2s;
}
.card:not(:first-child) {
margin-left: -2rem;
}
.card:not(:last-child):hover,
.card:not(:last-child):focus-within {
transform: translateY(-1rem);
~ .card {
transform: translateX(2rem);
}
}
</style>
The problem is that it doesn't work, it doesn't prefill the form, all i'm doing is trying to adapt some code that i know it works where i update a user's info, here's the code for that component, which works perfectly:
<template>
<div class="home">
<div class="body">
<h1>Actualiza Datos de Usuario</h1>
<div class="SignUp">
<img height="300" src="@/assets/Images/Usuario(1).png" alt="image slot" />
<b-form @submit.prevent="updateUsuario" class="pl-4">
<b-form-group id="input-group-1" label="User ID:" label-for="input-1">
<b-form-input
id="input-1"
v-model="proposedClientUser"
required
readonly
>
</b-form-input>
</b-form-group>
<b-form-group
id="input-group-2"
label="Tu contraseña:"
label-for="input-2"
>
<b-form-input
id="input-2"
v-model="proposedClientPassword"
type="password"
required
></b-form-input>
</b-form-group>
<b-form-group
id="input-group-3"
label="Tu Nombre Completo:"
label-for="input-3"
>
<b-form-input
id="input-3"
v-model="proposedClientName"
required
></b-form-input>
</b-form-group>
<b-form-group
id="input-group-4"
label="Tu numero de celular:"
label-for="input-4"
>
<b-form-input
id="input-4"
v-model="proposedClientPhone"
type="number"
required
></b-form-input>
</b-form-group>
<b-form-group
id="input-group-5"
label="Tu correo electronico:"
label-for="input-5"
>
<b-form-input
id="input-5"
v-model="proposedClientEmail"
type="email"
required
></b-form-input>
</b-form-group>
<b-form-group
id="input-group-6"
label="Tu Direccion:"
label-for="input-6"
>
<b-form-input
id="input-6"
v-model="proposedClientAddress"
required
></b-form-input>
</b-form-group>
<b-button block pill type="submit" variant="success"
>Actualiza tus datos</b-button
>
</b-form>
</div>
</div>
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
name: "UpdateClient",
data() {
return {
currentUser:{},
proposedClientUser:"",
proposedClientPassword:"",
proposedClientName:"",
proposedClientPhone:"",
proposedClientEmail:"",
proposedClientAddress:""
};
},
methods: {
updateUsuario() {
this.$store.dispatch("updateUsuario", [{
user: this.proposedClientUser,
password: this.proposedClientPassword,
client_name: this.proposedClientName,
client_phone: this.proposedClientPhone,
client_e_mail: this.proposedClientEmail,
client_address: this.proposedClientAddress
}, "clients"])
.then(({ data }) => {
if (data === "") {
alert("Error al actualizar datos");
} else {
alert ("Has actualizado tus datos")
this.$store.dispatch("logout");
location.replace('/login');
}
});
},
},
created() {
if (localStorage.getItem("user")) {
try {
this.currentUser = JSON.parse(localStorage.getItem("user"));
this.proposedClientUser = this.currentUser.user
this.proposedClientPassword = this.currentUser.password
this.proposedClientName = this.currentUser.client_name
this.proposedClientPhone = this.currentUser.client_phone
this.proposedClientEmail = this.currentUser.client_e_mail
this.proposedClientAddress = this.currentUser.client_address
} catch (e) {
localStorage.removeItem("user");
}
}
}
};
</script>
<style>
.body {
margin-bottom: 20px;
}
</style>
Any help would be appreciated here's an image showing the vue devtools, as you can see the form is not prefilling, also you can see the array
解决方案
- In
UpdatePets.vue
you already declared pets
and currentUser
on the props, don't need to declare it again in data()
- On the main
.vue
file, you are passing pet
prop, meanwhile the UpdatePets.vue
accepting pets
prop, change the prop on UpdatePets.vue
from pets
to pet
Other than that, it should work fine.
Check the minimalist demo i made here : https://codesandbox.io/s/priceless-elbakyan-ef2qu?file=/src/App.vue
这篇关于如何使用 vue 提交从对象数组中提取数据的预填充表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文