vue.js - 在 Vue 中跨组件传递数据
问题描述
我在我的 Django 项目的一个页面上加载了两个组件,一个用于从我的后端查询一些数据,另一个用于加载一些表单。
由于表单组件在页面上加载了四次(使用不同的参数),我无法从该组件查询数据,因为我会进行四次查询(每个组件一次),而我只需要做一次,所以我决定使用一个组件来进行查询,而表单组件应该只接收数据并将其与表单一起显示在页面上。
所以我有这个功能get_data.vue
:
..
methods: {
fetchBalance() {
fetch('MY-BACKEND')
.then(response => response.json())
.then(data => {
var freeBalance = data['freeBalance']
var totalBalance = data['totalBalance']
})
},
}
..
然后我有form.vue
<template>
...
</template>
<script>
export default {
props:{
order:{
type:String,
default:'amount'
},
side:{
type:String,
default:'price'
},
},
mounted() {
},
data() {
return {
name: '',
description: '',
output: ''
};
},
methods: {
formSubmit() {
let currentObj = this;
axios.post('MY-BACKEND', {
price: this.price,
amount: this.amount,
}
.then(function (response) {
currentObj.output = response.data;
}
.catch(function (error) {
currentObj.output = error;
});
},
}
}
</script>
不知何故,我需要访问变量freeBalance
并totalBalance
从get_data.vue
. form.vue
我怎样才能做到这一点?我正在考虑使用 Vuex,但我想看看是否有另一种方法可以在不使用 Vuex 的情况下做到这一点,因为这对于这项任务来说可能有点矫枉过正。
解决方案
将这些变量添加props
到您的form.vue
组件中(注意:我会将其重命名为其他名称,因为已经存在<form>
DOM 对象)并将它们传入。
// MyForm.vue (renamed from form.vue to avoid conflict with the DOM object of the same name)
export default {
props:{
order:{
type:String,
default:'amount'
},
side:{
type:String,
default:'price'
},
freeBalance: {
...
},
totalBalance: {
...
},
},
// get_data.vue
<template>
...
<my-form :free-balance="freeBalance" :total-balance="totalBalance" :order="..." :side="..."></my-form>
...
</template>
<script>
...
data() {
return {
...
// define your variables here to make them available to the template
freeBalance: null,
totalBalance: null,
}
},
methods: {
fetchBalance() {
fetch('MY-BACKEND')
.then(response => response.json())
.then(data => {
this.freeBalance = data['freeBalance']
// ^^^^^
this.totalBalance = data['totalBalance']
// ^^^^^
}),
},
}
在父组件的模板中使用道具名称时,请注意它们的 kebab-case。
推荐阅读
- regex - 如何根据词汇表列表拆分字符串?
- sqlite - 内部选择语句的不同结果
- python - 如何将列表作为值合并到字典中?
- opencv - 使用 Opencv 和 python 与 NVR 连接时,如何从海康威视 CCTV IP 摄像机获取图像进行图像处理?
- sql-server - SQL 表函数解析器
- java - 是否可以将项目导出为 jar 文件并将此 jar 导入其他项目以使用项目?
- python - 如何将python apt安装的.so模块复制到非默认python解释器
- node.js - 重构此函数以一致地使用“return”
- bash - bash 仅将最高(文件夹层次结构)位置结果放入变量中
- c++ - 使用系统功能重新启动具有正确权限的应用程序?