gpt4 book ai didi

javascript - 无法访问vue js中的props数据?

转载 作者:行者123 更新时间:2023-12-03 08:28:15 25 4
gpt4 key购买 nike

您好,我无法访问 Prop 数据。如果我在 chrome vue 开发工具 中看到 props 存在,但无法在创建或安装的钩子(Hook)中访问。

传递 Prop

 <Contradiction 
:patient="patient"
@openForm="toggleFormTable">
</Contradiction>

矛盾成分

name: "Contradiction",
props: {
patient: {
type: Object,
},
},
data() {
return {
patient_id: this.patient.id,
};
},
created() {
console.log("created hook", this.patient); // shows null
},
mounted() {
console.log("mounted hook", this.patient);//shows null
},

我不知道是什么原因,当我在 chrome 开发工具中看到 Patient props 存在但不在 console.log 中时。 props are there in the chorme dev tool screensh

最佳答案

从注释中澄清 patent 不是直接在父组件中设置后,您可以将 patent_id 定义为 compulated 属性:

const Contradiction = Vue.component('contradiction', {
template: '#contradiction',
props: { patient: { type: Object } },
computed: {
patient_id() { if(this.patient) return this.patient.id; }
}
});

new Vue({
el: '#app',
components: { Contradiction },
data() { return { patient: null } },
mounted() { setTimeout(() => this.patient = {id:1}, 3000); },
methods: {
toggleFormTable() {}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<div>
<Contradiction :patient="patient" @openForm="toggleFormTable"/>
</div>
</div>

<template id="contradiction">
<div>patient id: {{patient_id}}</div>
</template>

更好的解决方案是保留您的实现,并且仅在设置了 prop 时才渲染子组件:

const Contradiction = Vue.component('contradiction', {
template: '#contradiction',
props: { patient: { type: Object } },
data() { return { patient_id: this.patient.id } }
});

new Vue({
el: '#app',
components: { Contradiction },
data() { return { patient: null } },
mounted() { setTimeout(() => this.patient = {id:1}, 3000); },
methods: {
toggleFormTable() {}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<div>
<Contradiction v-if="patient" :patient="patient" @openForm="toggleFormTable"/>
</div>
</div>

<template id="contradiction">
<div>patient id: {{patient_id}}</div>
</template>

关于javascript - 无法访问vue js中的props数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65972916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com