vue.js - 如何将输入数据值从子组件数据对象发送到父组件?
问题描述
我正在尝试通过数据对象'data()'将输入数据变量从子组件表单发送到父组件。我已经看到vuejs 从子组件文章中更新父数据并尝试这样做,但是我无法通过事件 $emit 捕获的数据对象。你能帮帮我吗?
父组件:
<script>
import inputform from '../components/form.vue';
import axios from 'axios';
export default {
name: 'helloword',
data() {
return {
}
},
components: {
inputform
},
methods: {
submit() {
const path = 'http://127.0.0.1:5000';
axios.post(path, {
name: inputform.data()
})
.then(() => {
const result = 'Sucess!';
console.log(result);
})
.catch((error) => {
console.log(error);
})
}
}
}
</script>
子组件:
<template>
<div>
<table>
<thead>
<th>Name</th>
<th>Email</th>
<th>Age</th>
</thead>
<tr>
<td><input type="text" id="name" v-model="details.name" @focusout="inputdata"></td>
<td><input type="text" id="name1" v-model="details.name1" @focusout="inputdata" ></td>
<td><input type="number" id="age" v-model="details.age" @focusout="inputdata" ></td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: "inputform",
data() {
return {
details: {
name: '',
name1: '',
age: ''
}
}
},
methods: {
inputdata() {
this.$emit("input_data", this.details)
}
}
}
</script>
<style scoped>
</style>
因此,寻求帮助将变量数据从子组件发送到父组件,并使用父组件的 axios 向 API 执行提交操作。如果还有其他更好的方法请告诉我。谢谢。
解决方案
首先,您应该将最多两个参数传递给 $emit 方法,这是文档:https ://vuejs.org/v2/api/#vm-emit ,第二个是v-on:
之前的 v-models 是额外的。所以解决方案你可以在一个对象中传递这个数据而不是三个数据,所以代码将是这样的:
data() {
return {
name: '',
email: '',
age: '',
}
},
methods: {
inputdata() {
this.$emit("input", {
name: this.name,
email: this.email,
age: this.age
})
}
}
或者我更喜欢的选项将所有内容放在这样的表单数据中
<template>
<div>
<table>
<thead>
<th>Name</th>
<th>Email</th>
<th>Age</th>
</thead>
<tr>
<td><input type="text" id="name" v-model="form.name"></td>
<td><input type="email" id="email" v-model="form.email"></td>
<td><input type="number" id="age" v-model="form.age"></td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: "inputform",
data() {
return {
form: {
name: '',
email: '',
age: '',
}
}
},
methods: {
inputdata() {
this.$emit("input", this.form)
}
}
}
</script>
推荐阅读
- google-chrome-devtools - 如何查看响应原因短语
- python - 如何将字符串附加到 Python 字典中的现有值
- java - 如何在 vert.x 中为集合定义默认编解码器?
- python - 无法使用 selenium python 找到信用卡号的元素
- c# - System.Data.SqlClient.SqlException:'C# 中的'附近语法不正确
- c# - 如何在数据库第一个EF中定义两个不与数据注释组合的外键?
- r - R - 正弦线性模型中的高估预测函数
- php - 无法向同一页面发出 ajax 异步发布请求
- python - Pylint 与 pytorch:有没有办法告诉 pylint 在不同的地方寻找模块?
- java - Spring Session with JDBC - 如何使用单独的数据库作为会话存储