【发布时间】:2021-02-16 12:34:28
【问题描述】:
vue 新手,难以理解数据是如何在组件之间来回传递的。我知道 props 并在 parent/child、child/parent 上发出,但我不太明白它们在我的情况下是如何工作的。我有两个组件:一个名为“Letters”的父组件和一个名为“ClaimantSearch”的子组件。索赔人搜索根据对烧瓶后端的调用返回有关人员的数据:
<div>
<b-form @submit="onSubmit" class="w-100">
<b-form-group id="form-title-group"
label="Claim Number:"
label-for="form-claim-number-input">
<b-form-input id="form-claim-number-input"
type="text"
v-model="claimNumberForm.claimNumber"
required
placeholder="Enter claim number">
</b-form-input>
<button
type="button"
class="btn btn-warning btn-sm"
@click="getClaimant(claimNumber)">
Get Claimant
</button>
</b-form-group>
</b-form>
<span v-if="claimant">
<p> {{ claimant.name }} </p>
<p> {{ claimant.address1 }} </p>
<p> {{ claimant.address2 }} </p>
<p> {{ claimant.city }}, {{ claimant.state }} </p>
<p> {{ claimant.zip }} </p>
</span>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
claimant: '',
claimNumberForm: {
claimNumber: '',
},
};
},
methods: {
getClaimant(number) {
const path = `http://localhost:5000/claimant/${number}`;
axios.get(path)
.then((res) => {
this.claimant = res.data.claimant;
})
.catch((error) => {
// eslint-disable-next-line
console.error(error);
});
},
onSubmit(evt) {
evt.preventDefault();
this.getClaimant(this.claimNumberForm.claimNumber);
},
},
};
</script>
然后我有一个 Letters 父组件:
<template>
<div>
<claimant></claimant>
</div>
</template>
<script>
// import axios from 'axios';
import ClaimantSearch from './ClaimantSearch.vue';
export default {
data() {
return {
claimant: '',
claimNumberForm: {
claimNumber: '',
},
};
},
components: {
claimant: ClaimantSearch,
},
methods: {
},
};
</script>
如果有意义的话,我想做的是在<claimant> 标记之外访问{{claimant}}。所以在 Letters 里面我想做这样的事情:
<template>
<div>
<div>
<claimant></claimant>
</div>
<div>
Dear Mr. {{claimant.name}},
Please get bent. Sincerly, crappy insurance company.
</div>
</div>
</template>
【问题讨论】:
-
lmao,我真的希望你在保险业工作,并以此为生
-
另外,您正在寻找的是全局状态 -
vuex最适合它 -
太棒了,我读到了这个,但我不确定它是否对这个用例来说太过分了。谢谢。
标签: vue.js